1 /*
   2  * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/vmSymbols.hpp"
  27 #include "gc/shared/oopStorage.hpp"
  28 #include "gc/shared/oopStorageSet.hpp"
  29 #include "jfr/jfrEvents.hpp"
  30 #include "jfr/support/jfrThreadId.hpp"
  31 #include "logging/log.hpp"
  32 #include "logging/logStream.hpp"
  33 #include "memory/allocation.inline.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "oops/markWord.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "oops/oopHandle.inline.hpp"
  38 #include "oops/weakHandle.inline.hpp"
  39 #include "prims/jvmtiDeferredUpdates.hpp"
  40 #include "prims/jvmtiExport.hpp"
  41 #include "runtime/atomic.hpp"
  42 #include "runtime/continuationWrapper.inline.hpp"
  43 #include "runtime/globals.hpp"
  44 #include "runtime/handles.inline.hpp"
  45 #include "runtime/interfaceSupport.inline.hpp"
  46 #include "runtime/javaThread.inline.hpp"
  47 #include "runtime/lightweightSynchronizer.hpp"
  48 #include "runtime/mutexLocker.hpp"
  49 #include "runtime/objectMonitor.hpp"
  50 #include "runtime/objectMonitor.inline.hpp"
  51 #include "runtime/orderAccess.hpp"
  52 #include "runtime/osThread.hpp"
  53 #include "runtime/perfData.hpp"
  54 #include "runtime/safefetch.hpp"
  55 #include "runtime/safepointMechanism.inline.hpp"
  56 #include "runtime/sharedRuntime.hpp"
  57 #include "runtime/threads.hpp"
  58 #include "services/threadService.hpp"
  59 #include "utilities/debug.hpp"
  60 #include "utilities/dtrace.hpp"
  61 #include "utilities/globalDefinitions.hpp"
  62 #include "utilities/macros.hpp"
  63 #include "utilities/preserveException.hpp"
  64 #if INCLUDE_JFR
  65 #include "jfr/support/jfrFlush.hpp"
  66 #endif
  67 
  68 #ifdef DTRACE_ENABLED
  69 
  70 // Only bother with this argument setup if dtrace is available
  71 // TODO-FIXME: probes should not fire when caller is _blocked.  assert() accordingly.
  72 
  73 
  74 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread)                           \
  75   char* bytes = nullptr;                                                   \
  76   int len = 0;                                                             \
  77   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
  78   Symbol* klassname = obj->klass()->name();                                \
  79   if (klassname != nullptr) {                                              \
  80     bytes = (char*)klassname->bytes();                                     \
  81     len = klassname->utf8_length();                                        \
  82   }
  83 
  84 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis)            \
  85   {                                                                        \
  86     if (DTraceMonitorProbes) {                                             \
  87       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
  88       HOTSPOT_MONITOR_WAIT(jtid,                                           \
  89                            (monitor), bytes, len, (millis));               \
  90     }                                                                      \
  91   }
  92 
  93 #define HOTSPOT_MONITOR_contended__enter HOTSPOT_MONITOR_CONTENDED_ENTER
  94 #define HOTSPOT_MONITOR_contended__entered HOTSPOT_MONITOR_CONTENDED_ENTERED
  95 #define HOTSPOT_MONITOR_contended__exit HOTSPOT_MONITOR_CONTENDED_EXIT
  96 #define HOTSPOT_MONITOR_notify HOTSPOT_MONITOR_NOTIFY
  97 #define HOTSPOT_MONITOR_notifyAll HOTSPOT_MONITOR_NOTIFYALL
  98 
  99 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread)                  \
 100   {                                                                        \
 101     if (DTraceMonitorProbes) {                                             \
 102       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 103       HOTSPOT_MONITOR_##probe(jtid,                                        \
 104                               (uintptr_t)(monitor), bytes, len);           \
 105     }                                                                      \
 106   }
 107 
 108 #else //  ndef DTRACE_ENABLED
 109 
 110 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon)    {;}
 111 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon)          {;}
 112 
 113 #endif // ndef DTRACE_ENABLED
 114 
 115 DEBUG_ONLY(static volatile bool InitDone = false;)
 116 
 117 OopStorage* ObjectMonitor::_oop_storage = nullptr;
 118 
 119 OopHandle ObjectMonitor::_vthread_cxq_head;
 120 ParkEvent* ObjectMonitor::_vthread_unparker_ParkEvent = nullptr;
 121 
 122 static void post_virtual_thread_pinned_event(JavaThread* current, const char* reason) {
 123   EventVirtualThreadPinned e;
 124   if (e.should_commit()) {
 125     e.set_pinnedReason(reason);
 126     e.set_carrierThread(JFR_JVM_THREAD_ID(current));
 127     e.commit();
 128   }
 129 }
 130 
 131 // -----------------------------------------------------------------------------
 132 // Theory of operations -- Monitors lists, thread residency, etc:
 133 //
 134 // * A thread acquires ownership of a monitor by successfully
 135 //   CAS()ing the _owner field from null to non-null.
 136 //
 137 // * Invariant: A thread appears on at most one monitor list --
 138 //   cxq, EntryList or WaitSet -- at any one time.
 139 //
 140 // * Contending threads "push" themselves onto the cxq with CAS
 141 //   and then spin/park.
 142 //
 143 // * After a contending thread eventually acquires the lock it must
 144 //   dequeue itself from either the EntryList or the cxq.
 145 //
 146 // * The exiting thread identifies and unparks an "heir presumptive"
 147 //   tentative successor thread on the EntryList.  Critically, the
 148 //   exiting thread doesn't unlink the successor thread from the EntryList.
 149 //   After having been unparked, the wakee will recontend for ownership of
 150 //   the monitor.   The successor (wakee) will either acquire the lock or
 151 //   re-park itself.
 152 //
 153 //   Succession is provided for by a policy of competitive handoff.
 154 //   The exiting thread does _not_ grant or pass ownership to the
 155 //   successor thread.  (This is also referred to as "handoff" succession").
 156 //   Instead the exiting thread releases ownership and possibly wakes
 157 //   a successor, so the successor can (re)compete for ownership of the lock.
 158 //   If the EntryList is empty but the cxq is populated the exiting
 159 //   thread will drain the cxq into the EntryList.  It does so by
 160 //   by detaching the cxq (installing null with CAS) and folding
 161 //   the threads from the cxq into the EntryList.  The EntryList is
 162 //   doubly linked, while the cxq is singly linked because of the
 163 //   CAS-based "push" used to enqueue recently arrived threads (RATs).
 164 //
 165 // * Concurrency invariants:
 166 //
 167 //   -- only the monitor owner may access or mutate the EntryList.
 168 //      The mutex property of the monitor itself protects the EntryList
 169 //      from concurrent interference.
 170 //   -- Only the monitor owner may detach the cxq.
 171 //
 172 // * The monitor entry list operations avoid locks, but strictly speaking
 173 //   they're not lock-free.  Enter is lock-free, exit is not.
 174 //   For a description of 'Methods and apparatus providing non-blocking access
 175 //   to a resource,' see U.S. Pat. No. 7844973.
 176 //
 177 // * The cxq can have multiple concurrent "pushers" but only one concurrent
 178 //   detaching thread.  This mechanism is immune from the ABA corruption.
 179 //   More precisely, the CAS-based "push" onto cxq is ABA-oblivious.
 180 //
 181 // * Taken together, the cxq and the EntryList constitute or form a
 182 //   single logical queue of threads stalled trying to acquire the lock.
 183 //   We use two distinct lists to improve the odds of a constant-time
 184 //   dequeue operation after acquisition (in the ::enter() epilogue) and
 185 //   to reduce heat on the list ends.  (c.f. Michael Scott's "2Q" algorithm).
 186 //   A key desideratum is to minimize queue & monitor metadata manipulation
 187 //   that occurs while holding the monitor lock -- that is, we want to
 188 //   minimize monitor lock holds times.  Note that even a small amount of
 189 //   fixed spinning will greatly reduce the # of enqueue-dequeue operations
 190 //   on EntryList|cxq.  That is, spinning relieves contention on the "inner"
 191 //   locks and monitor metadata.
 192 //
 193 //   Cxq points to the set of Recently Arrived Threads attempting entry.
 194 //   Because we push threads onto _cxq with CAS, the RATs must take the form of
 195 //   a singly-linked LIFO.  We drain _cxq into EntryList at unlock-time when
 196 //   the unlocking thread notices that EntryList is null but _cxq is != null.
 197 //
 198 //   The EntryList is ordered by the prevailing queue discipline and
 199 //   can be organized in any convenient fashion, such as a doubly-linked list or
 200 //   a circular doubly-linked list.  Critically, we want insert and delete operations
 201 //   to operate in constant-time.  If we need a priority queue then something akin
 202 //   to Solaris' sleepq would work nicely.  Viz.,
 203 //   http://agg.eng/ws/on10_nightly/source/usr/src/uts/common/os/sleepq.c.
 204 //   Queue discipline is enforced at ::exit() time, when the unlocking thread
 205 //   drains the cxq into the EntryList, and orders or reorders the threads on the
 206 //   EntryList accordingly.
 207 //
 208 //   Barring "lock barging", this mechanism provides fair cyclic ordering,
 209 //   somewhat similar to an elevator-scan.
 210 //
 211 // * The monitor synchronization subsystem avoids the use of native
 212 //   synchronization primitives except for the narrow platform-specific
 213 //   park-unpark abstraction.  See the comments in os_solaris.cpp regarding
 214 //   the semantics of park-unpark.  Put another way, this monitor implementation
 215 //   depends only on atomic operations and park-unpark.  The monitor subsystem
 216 //   manages all RUNNING->BLOCKED and BLOCKED->READY transitions while the
 217 //   underlying OS manages the READY<->RUN transitions.
 218 //
 219 // * Waiting threads reside on the WaitSet list -- wait() puts
 220 //   the caller onto the WaitSet.
 221 //
 222 // * notify() or notifyAll() simply transfers threads from the WaitSet to
 223 //   either the EntryList or cxq.  Subsequent exit() operations will
 224 //   unpark the notifyee.  Unparking a notifee in notify() is inefficient -
 225 //   it's likely the notifyee would simply impale itself on the lock held
 226 //   by the notifier.
 227 
 228 // Check that object() and set_object() are called from the right context:
 229 static void check_object_context() {
 230 #ifdef ASSERT
 231   Thread* self = Thread::current();
 232   if (self->is_Java_thread()) {
 233     // Mostly called from JavaThreads so sanity check the thread state.
 234     JavaThread* jt = JavaThread::cast(self);
 235     switch (jt->thread_state()) {
 236     case _thread_in_vm:    // the usual case
 237     case _thread_in_Java:  // during deopt
 238       break;
 239     default:
 240       fatal("called from an unsafe thread state");
 241     }
 242     assert(jt->is_active_Java_thread(), "must be active JavaThread");
 243   } else {
 244     // However, ThreadService::get_current_contended_monitor()
 245     // can call here via the VMThread so sanity check it.
 246     assert(self->is_VM_thread(), "must be");
 247   }
 248 #endif // ASSERT
 249 }
 250 
 251 ObjectMonitor::ObjectMonitor(oop object) :
 252   _metadata(0),
 253   _object(_oop_storage, object),
 254   _owner(nullptr),
 255   _previous_owner_tid(0),
 256   _next_om(nullptr),
 257   _recursions(0),
 258   _EntryList(nullptr),
 259   _cxq(nullptr),
 260   _succ(nullptr),
 261   _SpinDuration(ObjectMonitor::Knob_SpinLimit),
 262   _contentions(0),
 263   _WaitSet(nullptr),
 264   _waiters(0),
 265   _WaitSetLock(0),
 266   _stack_locker(nullptr)
 267 { }
 268 
 269 ObjectMonitor::~ObjectMonitor() {
 270   _object.release(_oop_storage);
 271 }
 272 
 273 oop ObjectMonitor::object() const {
 274   check_object_context();
 275   return _object.resolve();
 276 }
 277 
 278 void ObjectMonitor::ExitOnSuspend::operator()(JavaThread* current) {
 279   if (current->is_suspended()) {
 280     _om->_recursions = 0;
 281     _om->_succ = nullptr;
 282     // Don't need a full fence after clearing successor here because of the call to exit().
 283     _om->exit(current, false /* not_suspended */);
 284     _om_exited = true;
 285 
 286     current->set_current_pending_monitor(_om);
 287   }
 288 }
 289 
 290 void ObjectMonitor::ClearSuccOnSuspend::operator()(JavaThread* current) {
 291   if (current->is_suspended()) {
 292     if (_om->_succ == current) {
 293       _om->_succ = nullptr;
 294       OrderAccess::fence(); // always do a full fence when successor is cleared
 295     }
 296   }
 297 }
 298 
 299 #define assert_mark_word_consistency()                                         \
 300   assert(UseObjectMonitorTable || object()->mark() == markWord::encode(this),  \
 301          "object mark must match encoded this: mark=" INTPTR_FORMAT            \
 302          ", encoded this=" INTPTR_FORMAT, object()->mark().value(),            \
 303          markWord::encode(this).value());
 304 
 305 // -----------------------------------------------------------------------------
 306 // Enter support
 307 
 308 bool ObjectMonitor::enter_is_async_deflating() {
 309   if (is_being_async_deflated()) {
 310     if (!UseObjectMonitorTable) {
 311       const oop l_object = object();
 312       if (l_object != nullptr) {
 313         // Attempt to restore the header/dmw to the object's header so that
 314         // we only retry once if the deflater thread happens to be slow.
 315         install_displaced_markword_in_object(l_object);
 316       }
 317     }
 318     return true;
 319   }
 320 
 321   return false;
 322 }
 323 
 324 bool ObjectMonitor::TryLockWithContentionMark(JavaThread* locking_thread, ObjectMonitorContentionMark& contention_mark) {
 325   assert(contention_mark._monitor == this, "must be");
 326   assert(!is_being_async_deflated(), "must be");
 327 
 328   void* prev_owner = try_set_owner_from(nullptr, locking_thread);
 329   bool success = false;
 330 
 331   if (prev_owner == nullptr) {
 332     assert(_recursions == 0, "invariant");
 333     success = true;
 334   } else if (prev_owner == owner_for(locking_thread)) {
 335     _recursions++;
 336     success = true;
 337   } else if (prev_owner == DEFLATER_MARKER) {
 338     // Racing with deflation.
 339     prev_owner = try_set_owner_from(DEFLATER_MARKER, locking_thread);
 340     if (prev_owner == DEFLATER_MARKER) {
 341       // We successfully cancelled the in-progress async deflation by
 342       // changing owner from DEFLATER_MARKER to current.  We now extend
 343       // the lifetime of the contention_mark (e.g. contentions++) here
 344       // to prevent the deflater thread from winning the last part of
 345       // the 2-part async deflation protocol after the regular
 346       // decrement occurs when the contention_mark goes out of
 347       // scope. ObjectMonitor::deflate_monitor() which is called by
 348       // the deflater thread will decrement contentions after it
 349       // recognizes that the async deflation was cancelled.
 350       contention_mark.extend();
 351       success = true;
 352     } else if (prev_owner == nullptr) {
 353       // At this point we cannot race with deflation as we have both incremented
 354       // contentions, seen contention > 0 and seen a DEFLATER_MARKER.
 355       // success will only be false if this races with something other than
 356       // deflation.
 357       prev_owner = try_set_owner_from(nullptr, locking_thread);
 358       success = prev_owner == nullptr;
 359     }
 360   }
 361   assert(!success || owner_raw() == owner_for(locking_thread), "must be");
 362 
 363   return success;
 364 }
 365 
 366 void ObjectMonitor::enter_for_with_contention_mark(JavaThread* locking_thread, ObjectMonitorContentionMark& contention_mark) {
 367   // Used by LightweightSynchronizer::inflate_and_enter in deoptimization path to enter for another thread.
 368   // The monitor is private to or already owned by locking_thread which must be suspended.
 369   // So this code may only contend with deflation.
 370   assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
 371   bool success = TryLockWithContentionMark(locking_thread, contention_mark);
 372 
 373   assert(success, "Failed to enter_for: locking_thread=" INTPTR_FORMAT
 374          ", this=" INTPTR_FORMAT "{owner=" INTPTR_FORMAT "}",
 375          p2i(locking_thread), p2i(this), p2i(owner_raw()));
 376 }
 377 
 378 bool ObjectMonitor::enter_for(JavaThread* locking_thread) {
 379   // Used by ObjectSynchronizer::enter_for() to enter for another thread.
 380   // The monitor is private to or already owned by locking_thread which must be suspended.
 381   // So this code may only contend with deflation.
 382   assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
 383 
 384   // Block out deflation as soon as possible.
 385   ObjectMonitorContentionMark contention_mark(this);
 386 
 387   // Check for deflation.
 388   if (enter_is_async_deflating()) {
 389     return false;
 390   }
 391 
 392   bool success = TryLockWithContentionMark(locking_thread, contention_mark);
 393 
 394   assert(success, "Failed to enter_for: locking_thread=" INTPTR_FORMAT
 395          ", this=" INTPTR_FORMAT "{owner=" INTPTR_FORMAT "}",
 396          p2i(locking_thread), p2i(this), p2i(owner_raw()));
 397   assert(owner_raw() == owner_for(locking_thread), "must be");
 398   return true;
 399 }
 400 
 401 bool ObjectMonitor::try_enter(JavaThread* current, bool check_for_recursion) {
 402   // TryLock avoids the CAS and handles deflation.
 403   TryLockResult r = TryLock(current);
 404   if (r == TryLockResult::Success) {
 405     assert(_recursions == 0, "invariant");
 406     return true;
 407   }
 408 
 409   // If called from SharedRuntime::monitor_exit_helper(), we know that
 410   // this thread doesn't already own the lock.
 411   if (!check_for_recursion) {
 412     return false;
 413   }
 414 
 415   if (r == TryLockResult::HasOwner && owner() == owner_for(current)) {
 416     _recursions++;
 417     return true;
 418   }
 419 
 420   return false;
 421 }
 422 
 423 bool ObjectMonitor::spin_enter(JavaThread* current) {
 424   assert(current == JavaThread::current(), "must be");
 425 
 426   // Check for recursion.
 427   if (try_enter(current)) {
 428     return true;
 429   }
 430 
 431   // Check for deflation.
 432   if (enter_is_async_deflating()) {
 433     return false;
 434   }
 435 
 436   // We've encountered genuine contention.
 437 
 438   // Do one round of spinning.
 439   // Note that if we acquire the monitor from an initial spin
 440   // we forgo posting JVMTI events and firing DTRACE probes.
 441   if (TrySpin(current)) {
 442     assert(owner_raw() == owner_for(current), "must be current: owner=" INTPTR_FORMAT, p2i(owner_raw()));
 443     assert(_recursions == 0, "must be 0: recursions=" INTX_FORMAT, _recursions);
 444     assert_mark_word_consistency();
 445     return true;
 446   }
 447 
 448   return false;
 449 }
 450 
 451 bool ObjectMonitor::enter(JavaThread* current) {
 452   assert(current == JavaThread::current(), "must be");
 453 
 454   if (spin_enter(current)) {
 455     return true;
 456   }
 457 
 458   assert(owner_raw() != owner_for(current), "invariant");
 459   assert(_succ != current, "invariant");
 460   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 461   assert(current->thread_state() != _thread_blocked, "invariant");
 462 
 463   // Keep is_being_async_deflated stable across the rest of enter
 464   ObjectMonitorContentionMark contention_mark(this);
 465 
 466   // Check for deflation.
 467   if (enter_is_async_deflating()) {
 468     return false;
 469   }
 470 
 471   // At this point this ObjectMonitor cannot be deflated, finish contended enter
 472   enter_with_contention_mark(current, contention_mark);
 473   return true;
 474 }
 475 
 476 void ObjectMonitor::enter_with_contention_mark(JavaThread *current, ObjectMonitorContentionMark &cm) {
 477   assert(current == JavaThread::current(), "must be");
 478   assert(owner_raw() != current, "must be");
 479   assert(cm._monitor == this, "must be");
 480   assert(!is_being_async_deflated(), "must be");
 481 
 482   JFR_ONLY(JfrConditionalFlush<EventJavaMonitorEnter> flush(current);)
 483   EventJavaMonitorEnter event;
 484   if (event.is_started()) {
 485     event.set_monitorClass(object()->klass());
 486     // Set an address that is 'unique enough', such that events close in
 487     // time and with the same address are likely (but not guaranteed) to
 488     // belong to the same object.
 489     event.set_address((uintptr_t)this);
 490   }
 491 
 492   { // Change java thread status to indicate blocked on monitor enter.
 493     JavaThreadBlockedOnMonitorEnterState jtbmes(current, this);
 494 
 495     assert(current->current_pending_monitor() == nullptr, "invariant");
 496     current->set_current_pending_monitor(this);
 497 
 498     DTRACE_MONITOR_PROBE(contended__enter, this, object(), current);
 499     if (JvmtiExport::should_post_monitor_contended_enter()) {
 500       JvmtiExport::post_monitor_contended_enter(current, this);
 501 
 502       // The current thread does not yet own the monitor and does not
 503       // yet appear on any queues that would get it made the successor.
 504       // This means that the JVMTI_EVENT_MONITOR_CONTENDED_ENTER event
 505       // handler cannot accidentally consume an unpark() meant for the
 506       // ParkEvent associated with this ObjectMonitor.
 507     }
 508 
 509     ContinuationEntry* ce = current->last_continuation();
 510     if (ce != nullptr && ce->is_virtual_thread()) {
 511       int result = Continuation::try_preempt(current, ce->cont_oop(current), Continuation::freeze_on_monitorenter);
 512       if (result == freeze_ok) {
 513         bool acquired = VThreadMonitorEnter(current);
 514         if (acquired) {
 515           current->set_preemption_cancelled(true);
 516           if (JvmtiExport::should_post_monitor_contended_entered()) {
 517             // We are going to call thaw again after this and finish the VMTS
 518             // transition so no need to do it here. We will post the event there.
 519             current->set_contended_entered_monitor(this);
 520           }
 521         }
 522         current->set_current_pending_monitor(nullptr);
 523         DEBUG_ONLY(int state = java_lang_VirtualThread::state(current->vthread()));
 524         assert((acquired && current->preemption_cancelled() && state == java_lang_VirtualThread::RUNNING) ||
 525                (!acquired && !current->preemption_cancelled() && state == java_lang_VirtualThread::BLOCKING), "invariant");
 526         return;
 527       }
 528       if (result == freeze_pinned_native) {
 529         post_virtual_thread_pinned_event(current, "Native frame or <clinit> on stack");
 530       } else if (result == freeze_unsupported) {
 531         post_virtual_thread_pinned_event(current, "Native frame or <clinit> or monitors on stack");
 532       }
 533     }
 534 
 535     OSThreadContendState osts(current->osthread());
 536 
 537     assert(current->thread_state() == _thread_in_vm, "invariant");
 538 
 539     for (;;) {
 540       ExitOnSuspend eos(this);
 541       {
 542         ThreadBlockInVMPreprocess<ExitOnSuspend> tbivs(current, eos, true /* allow_suspend */);
 543         EnterI(current);
 544         current->set_current_pending_monitor(nullptr);
 545         // We can go to a safepoint at the end of this block. If we
 546         // do a thread dump during that safepoint, then this thread will show
 547         // as having "-locked" the monitor, but the OS and java.lang.Thread
 548         // states will still report that the thread is blocked trying to
 549         // acquire it.
 550         // If there is a suspend request, ExitOnSuspend will exit the OM
 551         // and set the OM as pending.
 552       }
 553       if (!eos.exited()) {
 554         // ExitOnSuspend did not exit the OM
 555         assert(owner_raw() == owner_for(current), "invariant");
 556         break;
 557       }
 558     }
 559 
 560     // We've just gotten past the enter-check-for-suspend dance and we now own
 561     // the monitor free and clear.
 562   }
 563 
 564   assert(contentions() >= 0, "must not be negative: contentions=%d", contentions());
 565 
 566   // Must either set _recursions = 0 or ASSERT _recursions == 0.
 567   assert(_recursions == 0, "invariant");
 568   assert(owner_raw() == owner_for(current), "invariant");
 569   assert(_succ != current, "invariant");
 570   assert_mark_word_consistency();
 571 
 572   // The thread -- now the owner -- is back in vm mode.
 573   // Report the glorious news via TI,DTrace and jvmstat.
 574   // The probe effect is non-trivial.  All the reportage occurs
 575   // while we hold the monitor, increasing the length of the critical
 576   // section.  Amdahl's parallel speedup law comes vividly into play.
 577   //
 578   // Another option might be to aggregate the events (thread local or
 579   // per-monitor aggregation) and defer reporting until a more opportune
 580   // time -- such as next time some thread encounters contention but has
 581   // yet to acquire the lock.  While spinning that thread could
 582   // spinning we could increment JVMStat counters, etc.
 583 
 584   DTRACE_MONITOR_PROBE(contended__entered, this, object(), current);
 585   if (JvmtiExport::should_post_monitor_contended_entered()) {
 586     JvmtiExport::post_monitor_contended_entered(current, this);
 587 
 588     // The current thread already owns the monitor and is not going to
 589     // call park() for the remainder of the monitor enter protocol. So
 590     // it doesn't matter if the JVMTI_EVENT_MONITOR_CONTENDED_ENTERED
 591     // event handler consumed an unpark() issued by the thread that
 592     // just exited the monitor.
 593   }
 594   if (event.should_commit()) {
 595     event.set_previousOwner(_previous_owner_tid);
 596     event.commit();
 597   }
 598   OM_PERFDATA_OP(ContendedLockAttempts, inc());
 599 }
 600 
 601 // Caveat: TryLock() is not necessarily serializing if it returns failure.
 602 // Callers must compensate as needed.
 603 
 604 ObjectMonitor::TryLockResult ObjectMonitor::TryLock(JavaThread* current) {
 605   void* own = owner_raw();
 606   void* first_own = own;
 607 
 608   for (;;) {
 609     if (own == DEFLATER_MARKER) {
 610       // Block out deflation as soon as possible.
 611       ObjectMonitorContentionMark contention_mark(this);
 612 
 613       // Check for deflation.
 614       if (enter_is_async_deflating()) {
 615         // Treat deflation as interference.
 616         return TryLockResult::Interference;
 617       }
 618       if (TryLockWithContentionMark(current, contention_mark)) {
 619         assert(_recursions == 0, "invariant");
 620         return TryLockResult::Success;
 621       } else {
 622         // Deflation won or change of owner; dont spin
 623         break;
 624       }
 625     } else if (own == nullptr) {
 626       void* prev_own = try_set_owner_from(nullptr, current);
 627       if (prev_own == nullptr) {
 628         assert(_recursions == 0, "invariant");
 629         return TryLockResult::Success;
 630       } else {
 631         // The lock had been free momentarily, but we lost the race to the lock.
 632         own = prev_own;
 633       }
 634     } else {
 635       // Retry doesn't make as much sense because the lock was just acquired.
 636       break;
 637     }
 638   }
 639   return first_own == own ? TryLockResult::HasOwner : TryLockResult::Interference;
 640 }
 641 
 642 // Deflate the specified ObjectMonitor if not in-use. Returns true if it
 643 // was deflated and false otherwise.
 644 //
 645 // The async deflation protocol sets owner to DEFLATER_MARKER and
 646 // makes contentions negative as signals to contending threads that
 647 // an async deflation is in progress. There are a number of checks
 648 // as part of the protocol to make sure that the calling thread has
 649 // not lost the race to a contending thread.
 650 //
 651 // The ObjectMonitor has been successfully async deflated when:
 652 //   (contentions < 0)
 653 // Contending threads that see that condition know to retry their operation.
 654 //
 655 bool ObjectMonitor::deflate_monitor(Thread* current) {
 656   if (is_busy()) {
 657     // Easy checks are first - the ObjectMonitor is busy so no deflation.
 658     return false;
 659   }
 660 
 661   const oop obj = object_peek();
 662 
 663   if (obj == nullptr) {
 664     // If the object died, we can recycle the monitor without racing with
 665     // Java threads. The GC already broke the association with the object.
 666     set_owner_from_raw(nullptr, DEFLATER_MARKER);
 667     assert(contentions() >= 0, "must be non-negative: contentions=%d", contentions());
 668     _contentions = INT_MIN; // minimum negative int
 669   } else {
 670     // Attempt async deflation protocol.
 671 
 672     // Set a null owner to DEFLATER_MARKER to force any contending thread
 673     // through the slow path. This is just the first part of the async
 674     // deflation dance.
 675     if (try_set_owner_from_raw(nullptr, DEFLATER_MARKER) != nullptr) {
 676       // The owner field is no longer null so we lost the race since the
 677       // ObjectMonitor is now busy.
 678       return false;
 679     }
 680 
 681     if (contentions() > 0 || _waiters != 0) {
 682       // Another thread has raced to enter the ObjectMonitor after
 683       // is_busy() above or has already entered and waited on
 684       // it which makes it busy so no deflation. Restore owner to
 685       // null if it is still DEFLATER_MARKER.
 686       if (try_set_owner_from_raw(DEFLATER_MARKER, nullptr) != DEFLATER_MARKER) {
 687         // Deferred decrement for the JT EnterI() that cancelled the async deflation.
 688         add_to_contentions(-1);
 689       }
 690       return false;
 691     }
 692 
 693     // Make a zero contentions field negative to force any contending threads
 694     // to retry. This is the second part of the async deflation dance.
 695     if (Atomic::cmpxchg(&_contentions, 0, INT_MIN) != 0) {
 696       // Contentions was no longer 0 so we lost the race since the
 697       // ObjectMonitor is now busy. Restore owner to null if it is
 698       // still DEFLATER_MARKER:
 699       if (try_set_owner_from_raw(DEFLATER_MARKER, nullptr) != DEFLATER_MARKER) {
 700         // Deferred decrement for the JT EnterI() that cancelled the async deflation.
 701         add_to_contentions(-1);
 702       }
 703       return false;
 704     }
 705   }
 706 
 707   // Sanity checks for the races:
 708   guarantee(owner_is_DEFLATER_MARKER(), "must be deflater marker");
 709   guarantee(contentions() < 0, "must be negative: contentions=%d",
 710             contentions());
 711   guarantee(_waiters == 0, "must be 0: waiters=%d", _waiters);
 712   guarantee(_cxq == nullptr, "must be no contending threads: cxq="
 713             INTPTR_FORMAT, p2i(_cxq));
 714   guarantee(_EntryList == nullptr,
 715             "must be no entering threads: EntryList=" INTPTR_FORMAT,
 716             p2i(_EntryList));
 717 
 718   if (obj != nullptr) {
 719     if (log_is_enabled(Trace, monitorinflation)) {
 720       ResourceMark rm;
 721       log_trace(monitorinflation)("deflate_monitor: object=" INTPTR_FORMAT
 722                                   ", mark=" INTPTR_FORMAT ", type='%s'",
 723                                   p2i(obj), obj->mark().value(),
 724                                   obj->klass()->external_name());
 725     }
 726   }
 727 
 728   if (UseObjectMonitorTable) {
 729     LightweightSynchronizer::deflate_monitor(current, obj, this);
 730   } else if (obj != nullptr) {
 731     // Install the old mark word if nobody else has already done it.
 732     install_displaced_markword_in_object(obj);
 733   }
 734 
 735   // We leave owner == DEFLATER_MARKER and contentions < 0
 736   // to force any racing threads to retry.
 737   return true;  // Success, ObjectMonitor has been deflated.
 738 }
 739 
 740 // Install the displaced mark word (dmw) of a deflating ObjectMonitor
 741 // into the header of the object associated with the monitor. This
 742 // idempotent method is called by a thread that is deflating a
 743 // monitor and by other threads that have detected a race with the
 744 // deflation process.
 745 void ObjectMonitor::install_displaced_markword_in_object(const oop obj) {
 746   assert(!UseObjectMonitorTable, "ObjectMonitorTable has no dmw");
 747   // This function must only be called when (owner == DEFLATER_MARKER
 748   // && contentions <= 0), but we can't guarantee that here because
 749   // those values could change when the ObjectMonitor gets moved from
 750   // the global free list to a per-thread free list.
 751 
 752   guarantee(obj != nullptr, "must be non-null");
 753 
 754   // Separate loads in is_being_async_deflated(), which is almost always
 755   // called before this function, from the load of dmw/header below.
 756 
 757   // _contentions and dmw/header may get written by different threads.
 758   // Make sure to observe them in the same order when having several observers.
 759   OrderAccess::loadload_for_IRIW();
 760 
 761   const oop l_object = object_peek();
 762   if (l_object == nullptr) {
 763     // ObjectMonitor's object ref has already been cleared by async
 764     // deflation or GC so we're done here.
 765     return;
 766   }
 767   assert(l_object == obj, "object=" INTPTR_FORMAT " must equal obj="
 768          INTPTR_FORMAT, p2i(l_object), p2i(obj));
 769 
 770   markWord dmw = header();
 771   // The dmw has to be neutral (not null, not locked and not marked).
 772   assert(dmw.is_neutral(), "must be neutral: dmw=" INTPTR_FORMAT, dmw.value());
 773 
 774   // Install displaced mark word if the object's header still points
 775   // to this ObjectMonitor. More than one racing caller to this function
 776   // can rarely reach this point, but only one can win.
 777   markWord res = obj->cas_set_mark(dmw, markWord::encode(this));
 778   if (res != markWord::encode(this)) {
 779     // This should be rare so log at the Info level when it happens.
 780     log_info(monitorinflation)("install_displaced_markword_in_object: "
 781                                "failed cas_set_mark: new_mark=" INTPTR_FORMAT
 782                                ", old_mark=" INTPTR_FORMAT ", res=" INTPTR_FORMAT,
 783                                dmw.value(), markWord::encode(this).value(),
 784                                res.value());
 785   }
 786 
 787   // Note: It does not matter which thread restored the header/dmw
 788   // into the object's header. The thread deflating the monitor just
 789   // wanted the object's header restored and it is. The threads that
 790   // detected a race with the deflation process also wanted the
 791   // object's header restored before they retry their operation and
 792   // because it is restored they will only retry once.
 793 }
 794 
 795 // Convert the fields used by is_busy() to a string that can be
 796 // used for diagnostic output.
 797 const char* ObjectMonitor::is_busy_to_string(stringStream* ss) {
 798   ss->print("is_busy: waiters=%d"
 799             ", contentions=%d"
 800             ", owner=" INTPTR_FORMAT
 801             ", cxq=" PTR_FORMAT
 802             ", EntryList=" PTR_FORMAT,
 803             _waiters,
 804             (contentions() > 0 ? contentions() : 0),
 805             owner_is_DEFLATER_MARKER()
 806                 // We report null instead of DEFLATER_MARKER here because is_busy()
 807                 // ignores DEFLATER_MARKER values.
 808                 ? p2i(nullptr)
 809                 : p2i(owner_raw()),
 810             p2i(_cxq),
 811             p2i(_EntryList));
 812   return ss->base();
 813 }
 814 
 815 void ObjectMonitor::EnterI(JavaThread* current) {
 816   assert(current->thread_state() == _thread_blocked, "invariant");
 817 
 818   // Try the lock - TATAS
 819   if (TryLock(current) == TryLockResult::Success) {
 820     assert(_succ != current, "invariant");
 821     assert(owner_raw() == owner_for(current), "invariant");
 822     return;
 823   }
 824 
 825   assert(InitDone, "Unexpectedly not initialized");
 826 
 827   // We try one round of spinning *before* enqueueing current.
 828   //
 829   // If the _owner is ready but OFFPROC we could use a YieldTo()
 830   // operation to donate the remainder of this thread's quantum
 831   // to the owner.  This has subtle but beneficial affinity
 832   // effects.
 833 
 834   if (TrySpin(current)) {
 835     assert(owner_raw() == owner_for(current), "invariant");
 836     assert(_succ != current, "invariant");
 837     return;
 838   }
 839 
 840   // The Spin failed -- Enqueue and park the thread ...
 841   assert(_succ != current, "invariant");
 842   assert(owner_raw() != owner_for(current), "invariant");
 843 
 844   // Enqueue "current" on ObjectMonitor's _cxq.
 845   //
 846   // Node acts as a proxy for current.
 847   // As an aside, if were to ever rewrite the synchronization code mostly
 848   // in Java, WaitNodes, ObjectMonitors, and Events would become 1st-class
 849   // Java objects.  This would avoid awkward lifecycle and liveness issues,
 850   // as well as eliminate a subset of ABA issues.
 851   // TODO: eliminate ObjectWaiter and enqueue either Threads or Events.
 852 
 853   ObjectWaiter node(current);
 854   current->_ParkEvent->reset();
 855   node._prev   = (ObjectWaiter*) 0xBAD;
 856   node.TState  = ObjectWaiter::TS_CXQ;
 857 
 858   // Push "current" onto the front of the _cxq.
 859   // Once on cxq/EntryList, current stays on-queue until it acquires the lock.
 860   // Note that spinning tends to reduce the rate at which threads
 861   // enqueue and dequeue on EntryList|cxq.
 862   ObjectWaiter* nxt;
 863   for (;;) {
 864     node._next = nxt = _cxq;
 865     if (Atomic::cmpxchg(&_cxq, nxt, &node) == nxt) break;
 866 
 867     // Interference - the CAS failed because _cxq changed.  Just retry.
 868     // As an optional optimization we retry the lock.
 869     if (TryLock(current) == TryLockResult::Success) {
 870       assert(_succ != current, "invariant");
 871       assert(owner_raw() == owner_for(current), "invariant");
 872       return;
 873     }
 874   }
 875 
 876   // The lock might have been released while this thread was occupied queueing
 877   // itself onto _cxq.  To close the race and avoid "stranding" and
 878   // progress-liveness failure we must resample-retry _owner before parking.
 879   // Note the Dekker/Lamport duality: ST cxq; MEMBAR; LD Owner.
 880   // In this case the ST-MEMBAR is accomplished with CAS().
 881   //
 882   // TODO: Defer all thread state transitions until park-time.
 883   // Since state transitions are heavy and inefficient we'd like
 884   // to defer the state transitions until absolutely necessary,
 885   // and in doing so avoid some transitions ...
 886 
 887   // For virtual threads that are pinned, do a timed-park instead to
 888   // alleviate some deadlocks cases where succesor cannot run.
 889   static int MAX_RECHECK_INTERVAL = 1000;
 890   int recheck_interval = 1;
 891   bool do_timed_parked = false;
 892   ContinuationEntry* ce = current->last_continuation();
 893   if (ce != nullptr && ce->is_virtual_thread()) {
 894     do_timed_parked = true;
 895   }
 896 
 897   for (;;) {
 898 
 899     if (TryLock(current) == TryLockResult::Success) {
 900       break;
 901     }
 902     assert(owner_raw() != owner_for(current), "invariant");
 903 
 904     // park self
 905     if (do_timed_parked) {
 906       current->_ParkEvent->park((jlong) recheck_interval);
 907       // Increase the recheck_interval, but clamp the value.
 908       recheck_interval *= 8;
 909       if (recheck_interval > MAX_RECHECK_INTERVAL) {
 910         recheck_interval = MAX_RECHECK_INTERVAL;
 911       }
 912     } else {
 913       current->_ParkEvent->park();
 914     }
 915 
 916     if (TryLock(current) == TryLockResult::Success) {
 917       break;
 918     }
 919 
 920     // The lock is still contested.
 921 
 922     // Keep a tally of the # of futile wakeups.
 923     // Note that the counter is not protected by a lock or updated by atomics.
 924     // That is by design - we trade "lossy" counters which are exposed to
 925     // races during updates for a lower probe effect.
 926     // This PerfData object can be used in parallel with a safepoint.
 927     // See the work around in PerfDataManager::destroy().
 928     OM_PERFDATA_OP(FutileWakeups, inc());
 929 
 930     // Assuming this is not a spurious wakeup we'll normally find _succ == current.
 931     // We can defer clearing _succ until after the spin completes
 932     // TrySpin() must tolerate being called with _succ == current.
 933     // Try yet another round of adaptive spinning.
 934     if (TrySpin(current)) {
 935       break;
 936     }
 937 
 938     // We can find that we were unpark()ed and redesignated _succ while
 939     // we were spinning.  That's harmless.  If we iterate and call park(),
 940     // park() will consume the event and return immediately and we'll
 941     // just spin again.  This pattern can repeat, leaving _succ to simply
 942     // spin on a CPU.
 943 
 944     if (_succ == current) _succ = nullptr;
 945 
 946     // Invariant: after clearing _succ a thread *must* retry _owner before parking.
 947     OrderAccess::fence();
 948   }
 949 
 950   // Egress :
 951   // current has acquired the lock -- Unlink current from the cxq or EntryList.
 952   // Normally we'll find current on the EntryList .
 953   // From the perspective of the lock owner (this thread), the
 954   // EntryList is stable and cxq is prepend-only.
 955   // The head of cxq is volatile but the interior is stable.
 956   // In addition, current.TState is stable.
 957 
 958   assert(owner_raw() == owner_for(current), "invariant");
 959 
 960   UnlinkAfterAcquire(current, &node);
 961   if (_succ == current) {
 962     _succ = nullptr;
 963     // Note that we don't need to do OrderAccess::fence() after clearing
 964     // _succ here, since we own the lock.
 965   }
 966 
 967   // We've acquired ownership with CAS().
 968   // CAS is serializing -- it has MEMBAR/FENCE-equivalent semantics.
 969   // But since the CAS() this thread may have also stored into _succ,
 970   // EntryList or cxq.  These meta-data updates must be
 971   // visible __before this thread subsequently drops the lock.
 972   // Consider what could occur if we didn't enforce this constraint --
 973   // STs to monitor meta-data and user-data could reorder with (become
 974   // visible after) the ST in exit that drops ownership of the lock.
 975   // Some other thread could then acquire the lock, but observe inconsistent
 976   // or old monitor meta-data and heap data.  That violates the JMM.
 977   // To that end, the exit() operation must have at least STST|LDST
 978   // "release" barrier semantics.  Specifically, there must be at least a
 979   // STST|LDST barrier in exit() before the ST of null into _owner that drops
 980   // the lock.   The barrier ensures that changes to monitor meta-data and data
 981   // protected by the lock will be visible before we release the lock, and
 982   // therefore before some other thread (CPU) has a chance to acquire the lock.
 983   // See also: http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
 984   //
 985   // Critically, any prior STs to _succ or EntryList must be visible before
 986   // the ST of null into _owner in the *subsequent* (following) corresponding
 987   // monitorexit.
 988 
 989   return;
 990 }
 991 
 992 // ReenterI() is a specialized inline form of the latter half of the
 993 // contended slow-path from EnterI().  We use ReenterI() only for
 994 // monitor reentry in wait().
 995 //
 996 // In the future we should reconcile EnterI() and ReenterI().
 997 
 998 void ObjectMonitor::ReenterI(JavaThread* current, ObjectWaiter* currentNode) {
 999   assert(current != nullptr, "invariant");
1000   assert(current->thread_state() != _thread_blocked, "invariant");
1001   assert(currentNode != nullptr, "invariant");
1002   assert(currentNode->_thread == current, "invariant");
1003   assert(_waiters > 0, "invariant");
1004   assert_mark_word_consistency();
1005 
1006   for (;;) {
1007     uint8_t v = currentNode->TState;
1008     guarantee(v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant");
1009     assert(owner_raw() != owner_for(current), "invariant");
1010 
1011     // This thread has been notified so try to reacquire the lock.
1012     if (TryLock(current) == TryLockResult::Success) {
1013       break;
1014     }
1015 
1016     // If that fails, spin again.  Note that spin count may be zero so the above TryLock
1017     // is necessary.
1018     if (TrySpin(current)) {
1019         break;
1020     }
1021 
1022     {
1023       OSThreadContendState osts(current->osthread());
1024 
1025       assert(current->thread_state() == _thread_in_vm, "invariant");
1026 
1027       {
1028         ClearSuccOnSuspend csos(this);
1029         ThreadBlockInVMPreprocess<ClearSuccOnSuspend> tbivs(current, csos, true /* allow_suspend */);
1030         current->_ParkEvent->park();
1031       }
1032     }
1033 
1034     // Try again, but just so we distinguish between futile wakeups and
1035     // successful wakeups.  The following test isn't algorithmically
1036     // necessary, but it helps us maintain sensible statistics.
1037     if (TryLock(current) == TryLockResult::Success) {
1038       break;
1039     }
1040 
1041     // The lock is still contested.
1042 
1043     // Assuming this is not a spurious wakeup we'll normally
1044     // find that _succ == current.
1045     if (_succ == current) _succ = nullptr;
1046 
1047     // Invariant: after clearing _succ a contending thread
1048     // *must* retry  _owner before parking.
1049     OrderAccess::fence();
1050 
1051     // Keep a tally of the # of futile wakeups.
1052     // Note that the counter is not protected by a lock or updated by atomics.
1053     // That is by design - we trade "lossy" counters which are exposed to
1054     // races during updates for a lower probe effect.
1055     // This PerfData object can be used in parallel with a safepoint.
1056     // See the work around in PerfDataManager::destroy().
1057     OM_PERFDATA_OP(FutileWakeups, inc());
1058   }
1059 
1060   // current has acquired the lock -- Unlink current from the cxq or EntryList .
1061   // Normally we'll find current on the EntryList.
1062   // Unlinking from the EntryList is constant-time and atomic-free.
1063   // From the perspective of the lock owner (this thread), the
1064   // EntryList is stable and cxq is prepend-only.
1065   // The head of cxq is volatile but the interior is stable.
1066   // In addition, current.TState is stable.
1067 
1068   assert(owner_raw() == owner_for(current), "invariant");
1069   assert_mark_word_consistency();
1070   UnlinkAfterAcquire(current, currentNode);
1071   if (_succ == current) _succ = nullptr;
1072   assert(_succ != current, "invariant");
1073   currentNode->TState = ObjectWaiter::TS_RUN;
1074   OrderAccess::fence();      // see comments at the end of EnterI()
1075 }
1076 
1077 // This method is called from two places:
1078 // - On monitorenter contention with a null waiter.
1079 // - After Object.wait() times out or the target is interrupted to reenter the
1080 //   monitor, with the existing waiter.
1081 // For the Object.wait() case we do not delete the ObjectWaiter in case we
1082 // succesfully acquire the monitor since we are going to need it on return.
1083 bool ObjectMonitor::VThreadMonitorEnter(JavaThread* current, ObjectWaiter* waiter) {
1084   if (TryLock(current) == TryLockResult::Success) {
1085     assert(owner_raw() == owner_for(current), "invariant");
1086     assert(_succ != current, "invariant");
1087     return true;
1088   }
1089 
1090   oop vthread = current->vthread();
1091   ObjectWaiter* node = waiter != nullptr ? waiter : new ObjectWaiter(vthread, this);
1092   node->_prev   = (ObjectWaiter*) 0xBAD;
1093   node->TState  = ObjectWaiter::TS_CXQ;
1094 
1095   // Push node associated with vthread onto the front of the _cxq.
1096   ObjectWaiter* nxt;
1097   for (;;) {
1098     node->_next = nxt = _cxq;
1099     if (Atomic::cmpxchg(&_cxq, nxt, node) == nxt) break;
1100 
1101     // Interference - the CAS failed because _cxq changed.  Just retry.
1102     // As an optional optimization we retry the lock.
1103     if (TryLock(current) == TryLockResult::Success) {
1104       assert(owner_raw() == owner_for(current), "invariant");
1105       assert(_succ != current, "invariant");
1106       if (waiter == nullptr) delete node;  // for Object.wait() don't delete yet
1107       return true;
1108     }
1109   }
1110 
1111   // We have to try once more since owner could have exited monitor and checked
1112   // _cxq before we added the node to the queue.
1113   if (TryLock(current) == TryLockResult::Success) {
1114     assert(owner_raw() == owner_for(current), "invariant");
1115     UnlinkAfterAcquire(current, node);
1116     if (_succ == (JavaThread*)java_lang_Thread::thread_id(vthread)) _succ = nullptr;
1117     if (waiter == nullptr) delete node;  // for Object.wait() don't delete yet
1118     return true;
1119   }
1120 
1121   assert(java_lang_VirtualThread::state(vthread) == java_lang_VirtualThread::RUNNING, "wrong state for vthread");
1122   java_lang_VirtualThread::set_state(vthread, java_lang_VirtualThread::BLOCKING);
1123 
1124   // We didn't succeed in acquiring the monitor so increment _contentions and
1125   // save ObjectWaiter* in the chunk since we will need it when resuming execution.
1126   add_to_contentions(1);
1127   oop cont = java_lang_VirtualThread::continuation(vthread);
1128   stackChunkOop chunk  = jdk_internal_vm_Continuation::tail(cont);
1129   chunk->set_object_waiter(node);
1130   return false;
1131 }
1132 
1133 bool ObjectMonitor::resume_operation(JavaThread* current, ObjectWaiter* node, ContinuationWrapper& cont) {
1134   assert(java_lang_VirtualThread::state(current->vthread()) == java_lang_VirtualThread::RUNNING, "wrong state for vthread");
1135 
1136   if (node->is_wait() && !node->at_reenter()) {
1137     bool acquired_monitor = VThreadWaitReenter(current, node, cont);
1138     if (acquired_monitor) return true;
1139   }
1140 
1141   // Retry acquiring monitor...
1142 
1143   int state = node->TState;
1144   guarantee(state == ObjectWaiter::TS_ENTER || state == ObjectWaiter::TS_CXQ, "invariant");
1145 
1146   if (TryLock(current) == TryLockResult::Success) {
1147     VThreadEpilog(current, node);
1148     return true;
1149   }
1150 
1151   oop vthread = current->vthread();
1152   if (_succ == (JavaThread*)java_lang_Thread::thread_id(vthread)) _succ = nullptr;
1153 
1154   // Invariant: after clearing _succ a thread *must* retry _owner before parking.
1155   OrderAccess::fence();
1156 
1157   if (TryLock(current) == TryLockResult::Success) {
1158     VThreadEpilog(current, node);
1159     return true;
1160   }
1161 
1162   // The JT will read this variable on return to the resume_monitor_operation stub
1163   // and will unmount (enterSpecial frame removed and return to Continuation.run()).
1164   java_lang_VirtualThread::set_state(vthread, java_lang_VirtualThread::BLOCKING);
1165 
1166   return false;
1167 }
1168 
1169 void ObjectMonitor::VThreadEpilog(JavaThread* current, ObjectWaiter* node) {
1170   assert(owner_raw() == owner_for(current), "invariant");
1171   add_to_contentions(-1);
1172 
1173   oop vthread = current->vthread();
1174   int64_t threadid = java_lang_Thread::thread_id(vthread);
1175   if (_succ == (JavaThread*)threadid) _succ = nullptr;
1176 
1177   guarantee(_recursions == 0, "invariant");
1178 
1179   if (node->is_wait()) {
1180     _recursions = node->_recursions;   // restore the old recursion count
1181     _waiters--;                        // decrement the number of waiters
1182 
1183     if (node->_interrupted) {
1184       // We will throw at thaw end after finishing the mount transition.
1185       current->set_pending_interrupted_exception(true);
1186     }
1187   }
1188 
1189   assert(node->TState == ObjectWaiter::TS_ENTER || node->TState == ObjectWaiter::TS_CXQ, "");
1190   UnlinkAfterAcquire(current, node);
1191   delete node;
1192 
1193   oop cont = java_lang_VirtualThread::continuation(vthread);
1194   stackChunkOop chunk  = jdk_internal_vm_Continuation::tail(cont);
1195   chunk->set_object_waiter(nullptr);
1196 
1197   if (JvmtiExport::should_post_monitor_contended_entered()) {
1198     // We are going to call thaw again after this and finish the VMTS
1199     // transition so no need to do it here. We will post the event there.
1200     current->set_contended_entered_monitor(this);
1201   }
1202 }
1203 
1204 // By convention we unlink a contending thread from EntryList|cxq immediately
1205 // after the thread acquires the lock in ::enter().  Equally, we could defer
1206 // unlinking the thread until ::exit()-time.
1207 
1208 void ObjectMonitor::UnlinkAfterAcquire(JavaThread* current, ObjectWaiter* currentNode) {
1209   assert(owner_raw() == owner_for(current), "invariant");
1210   assert((!currentNode->is_vthread() && currentNode->thread() == current) ||
1211          (currentNode->is_vthread() && currentNode->vthread() == current->vthread()), "invariant");
1212 
1213   if (currentNode->TState == ObjectWaiter::TS_ENTER) {
1214     // Normal case: remove current from the DLL EntryList .
1215     // This is a constant-time operation.
1216     ObjectWaiter* nxt = currentNode->_next;
1217     ObjectWaiter* prv = currentNode->_prev;
1218     if (nxt != nullptr) nxt->_prev = prv;
1219     if (prv != nullptr) prv->_next = nxt;
1220     if (currentNode == _EntryList) _EntryList = nxt;
1221     assert(nxt == nullptr || nxt->TState == ObjectWaiter::TS_ENTER, "invariant");
1222     assert(prv == nullptr || prv->TState == ObjectWaiter::TS_ENTER, "invariant");
1223   } else {
1224     assert(currentNode->TState == ObjectWaiter::TS_CXQ, "invariant");
1225     // Inopportune interleaving -- current is still on the cxq.
1226     // This usually means the enqueue of self raced an exiting thread.
1227     // Normally we'll find current near the front of the cxq, so
1228     // dequeueing is typically fast.  If needbe we can accelerate
1229     // this with some MCS/CHL-like bidirectional list hints and advisory
1230     // back-links so dequeueing from the interior will normally operate
1231     // in constant-time.
1232     // Dequeue current from either the head (with CAS) or from the interior
1233     // with a linear-time scan and normal non-atomic memory operations.
1234     // CONSIDER: if current is on the cxq then simply drain cxq into EntryList
1235     // and then unlink current from EntryList.  We have to drain eventually,
1236     // so it might as well be now.
1237 
1238     ObjectWaiter* v = _cxq;
1239     assert(v != nullptr, "invariant");
1240     if (v != currentNode || Atomic::cmpxchg(&_cxq, v, currentNode->_next) != v) {
1241       // The CAS above can fail from interference IFF a "RAT" arrived.
1242       // In that case current must be in the interior and can no longer be
1243       // at the head of cxq.
1244       if (v == currentNode) {
1245         assert(_cxq != v, "invariant");
1246         v = _cxq;          // CAS above failed - start scan at head of list
1247       }
1248       ObjectWaiter* p;
1249       ObjectWaiter* q = nullptr;
1250       for (p = v; p != nullptr && p != currentNode; p = p->_next) {
1251         q = p;
1252         assert(p->TState == ObjectWaiter::TS_CXQ, "invariant");
1253       }
1254       assert(v != currentNode, "invariant");
1255       assert(p == currentNode, "Node not found on cxq");
1256       assert(p != _cxq, "invariant");
1257       assert(q != nullptr, "invariant");
1258       assert(q->_next == p, "invariant");
1259       q->_next = p->_next;
1260     }
1261   }
1262 
1263 #ifdef ASSERT
1264   // Diagnostic hygiene ...
1265   currentNode->_prev  = (ObjectWaiter*) 0xBAD;
1266   currentNode->_next  = (ObjectWaiter*) 0xBAD;
1267   currentNode->TState = ObjectWaiter::TS_RUN;
1268 #endif
1269 }
1270 
1271 // -----------------------------------------------------------------------------
1272 // Exit support
1273 //
1274 // exit()
1275 // ~~~~~~
1276 // Note that the collector can't reclaim the objectMonitor or deflate
1277 // the object out from underneath the thread calling ::exit() as the
1278 // thread calling ::exit() never transitions to a stable state.
1279 // This inhibits GC, which in turn inhibits asynchronous (and
1280 // inopportune) reclamation of "this".
1281 //
1282 // We'd like to assert that: (THREAD->thread_state() != _thread_blocked) ;
1283 // There's one exception to the claim above, however.  EnterI() can call
1284 // exit() to drop a lock if the acquirer has been externally suspended.
1285 // In that case exit() is called with _thread_state == _thread_blocked,
1286 // but the monitor's _contentions field is > 0, which inhibits reclamation.
1287 //
1288 // This is the exit part of the locking protocol, often implemented in
1289 // C2_MacroAssembler::fast_unlock()
1290 //
1291 //   1. A release barrier ensures that changes to monitor meta-data
1292 //      (_succ, _EntryList, _cxq) and data protected by the lock will be
1293 //      visible before we release the lock.
1294 //   2. Release the lock by clearing the owner.
1295 //   3. A storeload MEMBAR is needed between releasing the owner and
1296 //      subsequently reading meta-data to safely determine if the lock is
1297 //      contended (step 4) without an elected successor (step 5).
1298 //   4. If both _EntryList and _cxq are null, we are done, since there is no
1299 //      other thread waiting on the lock to wake up. I.e. there is no
1300 //      contention.
1301 //   5. If there is a successor (_succ is non-null), we are done. The
1302 //      responsibility for guaranteeing progress-liveness has now implicitly
1303 //      been moved from the exiting thread to the successor.
1304 //   6. There are waiters in the entry list (_EntryList and/or cxq are
1305 //      non-null), but there is no successor (_succ is null), so we need to
1306 //      wake up (unpark) a waiting thread to avoid stranding.
1307 //
1308 // Note that since only the current lock owner can manipulate the _EntryList
1309 // or drain _cxq, we need to reacquire the lock before we can wake up
1310 // (unpark) a waiting thread.
1311 //
1312 // The CAS() in enter provides for safety and exclusion, while the
1313 // MEMBAR in exit provides for progress and avoids stranding.
1314 //
1315 // There is also the risk of a futile wake-up. If we drop the lock
1316 // another thread can reacquire the lock immediately, and we can
1317 // then wake a thread unnecessarily. This is benign, and we've
1318 // structured the code so the windows are short and the frequency
1319 // of such futile wakups is low.
1320 
1321 void ObjectMonitor::exit(JavaThread* current, bool not_suspended) {
1322   void* cur = owner_raw();
1323   if (owner_for(current) != cur) {
1324     // Apparent unbalanced locking ...
1325     // Naively we'd like to throw IllegalMonitorStateException.
1326     // As a practical matter we can neither allocate nor throw an
1327     // exception as ::exit() can be called from leaf routines.
1328     // see x86_32.ad Fast_Unlock() and the I1 and I2 properties.
1329     // Upon deeper reflection, however, in a properly run JVM the only
1330     // way we should encounter this situation is in the presence of
1331     // unbalanced JNI locking. TODO: CheckJNICalls.
1332     // See also: CR4414101
1333 #ifdef ASSERT
1334     LogStreamHandle(Error, monitorinflation) lsh;
1335     lsh.print_cr("ERROR: ObjectMonitor::exit(): thread=" INTPTR_FORMAT
1336                   " is exiting an ObjectMonitor it does not own.", p2i(current));
1337     lsh.print_cr("The imbalance is possibly caused by JNI locking.");
1338     print_debug_style_on(&lsh);
1339     assert(false, "Non-balanced monitor enter/exit!");
1340 #endif
1341     return;
1342   }
1343 
1344   if (_recursions != 0) {
1345     _recursions--;        // this is simple recursive enter
1346     return;
1347   }
1348 
1349 #if INCLUDE_JFR
1350   // get the owner's thread id for the MonitorEnter event
1351   // if it is enabled and the thread isn't suspended
1352   if (not_suspended && EventJavaMonitorEnter::is_enabled()) {
1353     _previous_owner_tid = JFR_THREAD_ID(current);
1354   }
1355 #endif
1356 
1357   for (;;) {
1358     assert(owner_for(current) == owner_raw(), "invariant");
1359 
1360     // Drop the lock.
1361     // release semantics: prior loads and stores from within the critical section
1362     // must not float (reorder) past the following store that drops the lock.
1363     // Uses a storeload to separate release_store(owner) from the
1364     // successor check. The try_set_owner_from() below uses cmpxchg() so
1365     // we get the fence down there.
1366     release_clear_owner(current);
1367     OrderAccess::storeload();
1368 
1369     if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != nullptr) {
1370       return;
1371     }
1372     // Other threads are blocked trying to acquire the lock.
1373 
1374     // Normally the exiting thread is responsible for ensuring succession,
1375     // but if this thread observes other successors are ready or other
1376     // entering threads are spinning after it has stored null into _owner
1377     // then it can exit without waking a successor.  The existence of
1378     // spinners or ready successors guarantees proper succession (liveness).
1379     // Responsibility passes to the ready or running successors.  The exiting
1380     // thread delegates the duty.  More precisely, if a successor already
1381     // exists this thread is absolved of the responsibility of waking
1382     // (unparking) one.
1383 
1384     // The _succ variable is critical to reducing futile wakeup frequency.
1385     // _succ identifies the "heir presumptive" thread that has been made
1386     // ready (unparked) but that has not yet run.  We need only one such
1387     // successor thread to guarantee progress.
1388     // See http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf
1389     // section 3.3 "Futile Wakeup Throttling" for details.
1390     //
1391     // Note that spinners in Enter() also set _succ non-null.
1392     // In the current implementation spinners opportunistically set
1393     // _succ so that exiting threads might avoid waking a successor.
1394     // Which means that the exiting thread could exit immediately without
1395     // waking a successor, if it observes a successor after it has dropped
1396     // the lock.  Note that the dropped lock needs to become visible to the
1397     // spinner.
1398 
1399     // It appears that an heir-presumptive (successor) must be made ready.
1400     // Only the current lock owner can manipulate the EntryList or
1401     // drain _cxq, so we need to reacquire the lock.  If we fail
1402     // to reacquire the lock the responsibility for ensuring succession
1403     // falls to the new owner.
1404 
1405     if (TryLock(current) != TryLockResult::Success) {
1406       // Some other thread acquired the lock (or the monitor was
1407       // deflated). Either way we are done.
1408       return;
1409     }
1410 
1411     guarantee(owner_raw() == owner_for(current), "invariant");
1412 
1413     ObjectWaiter* w = nullptr;
1414 
1415     w = _EntryList;
1416     if (w != nullptr) {
1417       // I'd like to write: guarantee (w->_thread != current).
1418       // But in practice an exiting thread may find itself on the EntryList.
1419       // Let's say thread T1 calls O.wait().  Wait() enqueues T1 on O's waitset and
1420       // then calls exit().  Exit release the lock by setting O._owner to null.
1421       // Let's say T1 then stalls.  T2 acquires O and calls O.notify().  The
1422       // notify() operation moves T1 from O's waitset to O's EntryList. T2 then
1423       // release the lock "O".  T2 resumes immediately after the ST of null into
1424       // _owner, above.  T2 notices that the EntryList is populated, so it
1425       // reacquires the lock and then finds itself on the EntryList.
1426       // Given all that, we have to tolerate the circumstance where "w" is
1427       // associated with current.
1428       assert(w->TState == ObjectWaiter::TS_ENTER, "invariant");
1429       ExitEpilog(current, w);
1430       return;
1431     }
1432 
1433     // If we find that both _cxq and EntryList are null then just
1434     // re-run the exit protocol from the top.
1435     w = _cxq;
1436     if (w == nullptr) continue;
1437 
1438     // Drain _cxq into EntryList - bulk transfer.
1439     // First, detach _cxq.
1440     // The following loop is tantamount to: w = swap(&cxq, nullptr)
1441     for (;;) {
1442       assert(w != nullptr, "Invariant");
1443       ObjectWaiter* u = Atomic::cmpxchg(&_cxq, w, (ObjectWaiter*)nullptr);
1444       if (u == w) break;
1445       w = u;
1446     }
1447 
1448     assert(w != nullptr, "invariant");
1449     assert(_EntryList == nullptr, "invariant");
1450 
1451     // Convert the LIFO SLL anchored by _cxq into a DLL.
1452     // The list reorganization step operates in O(LENGTH(w)) time.
1453     // It's critical that this step operate quickly as
1454     // "current" still holds the outer-lock, restricting parallelism
1455     // and effectively lengthening the critical section.
1456     // Invariant: s chases t chases u.
1457     // TODO-FIXME: consider changing EntryList from a DLL to a CDLL so
1458     // we have faster access to the tail.
1459 
1460     _EntryList = w;
1461     ObjectWaiter* q = nullptr;
1462     ObjectWaiter* p;
1463     for (p = w; p != nullptr; p = p->_next) {
1464       guarantee(p->TState == ObjectWaiter::TS_CXQ, "Invariant");
1465       p->TState = ObjectWaiter::TS_ENTER;
1466       p->_prev = q;
1467       q = p;
1468     }
1469 
1470     // We need to: ST EntryList; MEMBAR #storestore; ST _owner = nullptr
1471     // The MEMBAR is satisfied by the release_store() operation in ExitEpilog().
1472 
1473     // See if we can abdicate to a spinner instead of waking a thread.
1474     // A primary goal of the implementation is to reduce the
1475     // context-switch rate.
1476     if (_succ != nullptr) continue;
1477 
1478     w = _EntryList;
1479     if (w != nullptr) {
1480       guarantee(w->TState == ObjectWaiter::TS_ENTER, "invariant");
1481       ExitEpilog(current, w);
1482       return;
1483     }
1484   }
1485 }
1486 
1487 void ObjectMonitor::ExitEpilog(JavaThread* current, ObjectWaiter* Wakee) {
1488   assert(owner_raw() == owner_for(current), "invariant");
1489 
1490   // Exit protocol:
1491   // 1. ST _succ = wakee
1492   // 2. membar #loadstore|#storestore;
1493   // 2. ST _owner = nullptr
1494   // 3. unpark(wakee)
1495 
1496   oop vthread = nullptr;
1497   ParkEvent * Trigger;
1498   if (!Wakee->is_vthread()) {
1499     JavaThread* t = Wakee->thread();
1500     assert(t != nullptr, "");
1501     Trigger = t->_ParkEvent;
1502     _succ = t;
1503   } else {
1504     vthread = Wakee->vthread();
1505     assert(vthread != nullptr, "");
1506     Trigger = ObjectMonitor::vthread_unparker_ParkEvent();
1507     _succ = (JavaThread*)java_lang_Thread::thread_id(vthread);
1508   }
1509 
1510   // Hygiene -- once we've set _owner = nullptr we can't safely dereference Wakee again.
1511   // The thread associated with Wakee may have grabbed the lock and "Wakee" may be
1512   // out-of-scope (non-extant).
1513   Wakee  = nullptr;
1514 
1515   // Drop the lock.
1516   // Uses a fence to separate release_store(owner) from the LD in unpark().
1517   release_clear_owner(current);
1518   OrderAccess::fence();
1519 
1520   DTRACE_MONITOR_PROBE(contended__exit, this, object(), current);
1521 
1522   if (vthread == nullptr) {
1523     // Platform thread case
1524     Trigger->unpark();
1525   } else if (java_lang_VirtualThread::set_onWaitingList(vthread, _vthread_cxq_head)) {
1526     Trigger->unpark();
1527   }
1528 
1529   // Maintain stats and report events to JVMTI
1530   OM_PERFDATA_OP(Parks, inc());
1531 }
1532 
1533 // complete_exit exits a lock returning recursion count
1534 // complete_exit requires an inflated monitor
1535 // The _owner field is not always the Thread addr even with an
1536 // inflated monitor, e.g. the monitor can be inflated by a non-owning
1537 // thread due to contention.
1538 intx ObjectMonitor::complete_exit(JavaThread* current) {
1539   assert(InitDone, "Unexpectedly not initialized");
1540 
1541   void* cur = owner_raw();
1542   if (owner_for(current) != cur) {
1543     if (LockingMode == LM_LEGACY && is_stack_locker(current)) {
1544       assert(_recursions == 0, "internal state error");
1545       set_owner_from_BasicLock(current);  // Convert from BasicLock* to Thread*.
1546       _recursions = 0;
1547     }
1548   }
1549 
1550   guarantee(owner_for(current) == owner_raw(), "complete_exit not owner");
1551   intx save = _recursions; // record the old recursion count
1552   _recursions = 0;         // set the recursion level to be 0
1553   exit(current);           // exit the monitor
1554   guarantee(owner_raw() != owner_for(current), "invariant");
1555   return save;
1556 }
1557 
1558 // Checks that the current THREAD owns this monitor and causes an
1559 // immediate return if it doesn't. We don't use the CHECK macro
1560 // because we want the IMSE to be the only exception that is thrown
1561 // from the call site when false is returned. Any other pending
1562 // exception is ignored.
1563 #define CHECK_OWNER()                                                  \
1564   do {                                                                 \
1565     if (!check_owner(THREAD)) {                                        \
1566        assert(HAS_PENDING_EXCEPTION, "expected a pending IMSE here."); \
1567        return;                                                         \
1568      }                                                                 \
1569   } while (false)
1570 
1571 // Returns true if the specified thread owns the ObjectMonitor.
1572 // Otherwise returns false and throws IllegalMonitorStateException
1573 // (IMSE). If there is a pending exception and the specified thread
1574 // is not the owner, that exception will be replaced by the IMSE.
1575 bool ObjectMonitor::check_owner(TRAPS) {
1576   JavaThread* current = THREAD;
1577   void* cur = owner_raw();
1578   if (cur == owner_for(current)) {
1579     return true;
1580   }
1581   THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(),
1582              "current thread is not owner", false);
1583 }
1584 
1585 static inline bool is_excluded(const Klass* monitor_klass) {
1586   assert(monitor_klass != nullptr, "invariant");
1587   NOT_JFR_RETURN_(false);
1588   JFR_ONLY(return vmSymbols::jdk_jfr_internal_management_HiddenWait() == monitor_klass->name();)
1589 }
1590 
1591 static void post_monitor_wait_event(EventJavaMonitorWait* event,
1592                                     ObjectMonitor* monitor,
1593                                     uint64_t notifier_tid,
1594                                     jlong timeout,
1595                                     bool timedout) {
1596   assert(event != nullptr, "invariant");
1597   assert(monitor != nullptr, "invariant");
1598   const Klass* monitor_klass = monitor->object()->klass();
1599   if (is_excluded(monitor_klass)) {
1600     return;
1601   }
1602   event->set_monitorClass(monitor_klass);
1603   event->set_timeout(timeout);
1604   // Set an address that is 'unique enough', such that events close in
1605   // time and with the same address are likely (but not guaranteed) to
1606   // belong to the same object.
1607   event->set_address((uintptr_t)monitor);
1608   event->set_notifier(notifier_tid);
1609   event->set_timedOut(timedout);
1610   event->commit();
1611 }
1612 
1613 static void vthread_monitor_waited_event(JavaThread *current, ObjectWaiter* node, ContinuationWrapper& cont, EventJavaMonitorWait* event, jboolean timed_out) {
1614   // Since we might safepoint set the anchor so that the stack can we walked.
1615   assert(current->last_continuation() != nullptr, "");
1616   JavaFrameAnchor* anchor = current->frame_anchor();
1617   anchor->set_last_Java_sp(current->last_continuation()->entry_sp());
1618   anchor->set_last_Java_pc(current->last_continuation()->entry_pc());
1619 
1620   ContinuationWrapper::SafepointOp so(current, cont);
1621 
1622   JRT_BLOCK
1623     if (event->should_commit()) {
1624       long timeout = java_lang_VirtualThread::waitTimeout(current->vthread());
1625       post_monitor_wait_event(event, node->_monitor, node->_notifier_tid, timeout, timed_out);
1626     }
1627     if (JvmtiExport::should_post_monitor_waited()) {
1628       ThreadOnMonitorWaitedEvent tmwe(current);
1629       JvmtiExport::vthread_post_monitor_waited(current, node->_monitor, timed_out);
1630     }
1631   JRT_BLOCK_END
1632   current->frame_anchor()->clear();
1633 }
1634 
1635 // -----------------------------------------------------------------------------
1636 // Wait/Notify/NotifyAll
1637 //
1638 // Note: a subset of changes to ObjectMonitor::wait()
1639 // will need to be replicated in complete_exit
1640 void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) {
1641   JavaThread* current = THREAD;
1642 
1643   assert(InitDone, "Unexpectedly not initialized");
1644 
1645   CHECK_OWNER();  // Throws IMSE if not owner.
1646 
1647   EventJavaMonitorWait event;
1648 
1649   // check for a pending interrupt
1650   if (interruptible && current->is_interrupted(true) && !HAS_PENDING_EXCEPTION) {
1651     // post monitor waited event.  Note that this is past-tense, we are done waiting.
1652     if (JvmtiExport::should_post_monitor_waited()) {
1653       // Note: 'false' parameter is passed here because the
1654       // wait was not timed out due to thread interrupt.
1655       JvmtiExport::post_monitor_waited(current, this, false);
1656 
1657       // In this short circuit of the monitor wait protocol, the
1658       // current thread never drops ownership of the monitor and
1659       // never gets added to the wait queue so the current thread
1660       // cannot be made the successor. This means that the
1661       // JVMTI_EVENT_MONITOR_WAITED event handler cannot accidentally
1662       // consume an unpark() meant for the ParkEvent associated with
1663       // this ObjectMonitor.
1664     }
1665     if (event.should_commit()) {
1666       post_monitor_wait_event(&event, this, 0, millis, false);
1667     }
1668     THROW(vmSymbols::java_lang_InterruptedException());
1669     return;
1670   }
1671 
1672   current->set_current_waiting_monitor(this);
1673 
1674   ContinuationEntry* ce = current->last_continuation();
1675   if (interruptible && ce != nullptr && ce->is_virtual_thread()) {
1676     int result = Continuation::try_preempt(current, ce->cont_oop(current), Continuation::freeze_on_wait);
1677     if (result == freeze_ok) {
1678       VThreadWait(current, millis);
1679       current->set_current_waiting_monitor(nullptr);
1680       return;
1681     }
1682     if (result == freeze_pinned_native || result == freeze_unsupported) {
1683       const Klass* monitor_klass = object()->klass();
1684       if (!is_excluded(monitor_klass)) {
1685         if (result == freeze_pinned_native) {
1686           post_virtual_thread_pinned_event(current,"Native frame or <clinit> on stack");
1687         } else if (result == freeze_unsupported) {
1688           post_virtual_thread_pinned_event(current, "Native frame or <clinit> or monitors on stack");
1689         }
1690       }
1691     }
1692   }
1693 
1694   // create a node to be put into the queue
1695   // Critically, after we reset() the event but prior to park(), we must check
1696   // for a pending interrupt.
1697   ObjectWaiter node(current);
1698   node.TState = ObjectWaiter::TS_WAIT;
1699   current->_ParkEvent->reset();
1700   OrderAccess::fence();          // ST into Event; membar ; LD interrupted-flag
1701 
1702   // Enter the waiting queue, which is a circular doubly linked list in this case
1703   // but it could be a priority queue or any data structure.
1704   // _WaitSetLock protects the wait queue.  Normally the wait queue is accessed only
1705   // by the owner of the monitor *except* in the case where park()
1706   // returns because of a timeout of interrupt.  Contention is exceptionally rare
1707   // so we use a simple spin-lock instead of a heavier-weight blocking lock.
1708 
1709   Thread::SpinAcquire(&_WaitSetLock, "WaitSet - add");
1710   AddWaiter(&node);
1711   Thread::SpinRelease(&_WaitSetLock);
1712 
1713   intx save = _recursions;     // record the old recursion count
1714   _waiters++;                  // increment the number of waiters
1715   _recursions = 0;             // set the recursion level to be 1
1716   exit(current);               // exit the monitor
1717   guarantee(owner_raw() != owner_for(current), "invariant");
1718 
1719   // The thread is on the WaitSet list - now park() it.
1720   // On MP systems it's conceivable that a brief spin before we park
1721   // could be profitable.
1722   //
1723   // TODO-FIXME: change the following logic to a loop of the form
1724   //   while (!timeout && !interrupted && _notified == 0) park()
1725 
1726   int ret = OS_OK;
1727   int WasNotified = 0;
1728 
1729   // Need to check interrupt state whilst still _thread_in_vm
1730   bool interrupted = interruptible && current->is_interrupted(false);
1731 
1732   { // State transition wrappers
1733     OSThread* osthread = current->osthread();
1734     OSThreadWaitState osts(osthread, true);
1735 
1736     assert(current->thread_state() == _thread_in_vm, "invariant");
1737 
1738     {
1739       ClearSuccOnSuspend csos(this);
1740       ThreadBlockInVMPreprocess<ClearSuccOnSuspend> tbivs(current, csos, true /* allow_suspend */);
1741       if (interrupted || HAS_PENDING_EXCEPTION) {
1742         // Intentionally empty
1743       } else if (!node._notified) {
1744         if (millis <= 0) {
1745           current->_ParkEvent->park();
1746         } else {
1747           ret = current->_ParkEvent->park(millis);
1748         }
1749       }
1750     }
1751 
1752     // Node may be on the WaitSet, the EntryList (or cxq), or in transition
1753     // from the WaitSet to the EntryList.
1754     // See if we need to remove Node from the WaitSet.
1755     // We use double-checked locking to avoid grabbing _WaitSetLock
1756     // if the thread is not on the wait queue.
1757     //
1758     // Note that we don't need a fence before the fetch of TState.
1759     // In the worst case we'll fetch a old-stale value of TS_WAIT previously
1760     // written by the is thread. (perhaps the fetch might even be satisfied
1761     // by a look-aside into the processor's own store buffer, although given
1762     // the length of the code path between the prior ST and this load that's
1763     // highly unlikely).  If the following LD fetches a stale TS_WAIT value
1764     // then we'll acquire the lock and then re-fetch a fresh TState value.
1765     // That is, we fail toward safety.
1766 
1767     if (node.TState == ObjectWaiter::TS_WAIT) {
1768       Thread::SpinAcquire(&_WaitSetLock, "WaitSet - unlink");
1769       if (node.TState == ObjectWaiter::TS_WAIT) {
1770         DequeueSpecificWaiter(&node);       // unlink from WaitSet
1771         assert(!node._notified, "invariant");
1772         node.TState = ObjectWaiter::TS_RUN;
1773       }
1774       Thread::SpinRelease(&_WaitSetLock);
1775     }
1776 
1777     // The thread is now either on off-list (TS_RUN),
1778     // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ).
1779     // The Node's TState variable is stable from the perspective of this thread.
1780     // No other threads will asynchronously modify TState.
1781     guarantee(node.TState != ObjectWaiter::TS_WAIT, "invariant");
1782     OrderAccess::loadload();
1783     if (_succ == current) _succ = nullptr;
1784     WasNotified = node._notified;
1785 
1786     // Reentry phase -- reacquire the monitor.
1787     // re-enter contended monitor after object.wait().
1788     // retain OBJECT_WAIT state until re-enter successfully completes
1789     // Thread state is thread_in_vm and oop access is again safe,
1790     // although the raw address of the object may have changed.
1791     // (Don't cache naked oops over safepoints, of course).
1792 
1793     // post monitor waited event. Note that this is past-tense, we are done waiting.
1794     if (JvmtiExport::should_post_monitor_waited()) {
1795       JvmtiExport::post_monitor_waited(current, this, ret == OS_TIMEOUT);
1796 
1797       if (node._notified && _succ == current) {
1798         // In this part of the monitor wait-notify-reenter protocol it
1799         // is possible (and normal) for another thread to do a fastpath
1800         // monitor enter-exit while this thread is still trying to get
1801         // to the reenter portion of the protocol.
1802         //
1803         // The ObjectMonitor was notified and the current thread is
1804         // the successor which also means that an unpark() has already
1805         // been done. The JVMTI_EVENT_MONITOR_WAITED event handler can
1806         // consume the unpark() that was done when the successor was
1807         // set because the same ParkEvent is shared between Java
1808         // monitors and JVM/TI RawMonitors (for now).
1809         //
1810         // We redo the unpark() to ensure forward progress, i.e., we
1811         // don't want all pending threads hanging (parked) with none
1812         // entering the unlocked monitor.
1813         current->_ParkEvent->unpark();
1814       }
1815     }
1816 
1817     if (event.should_commit()) {
1818       post_monitor_wait_event(&event, this, node._notifier_tid, millis, ret == OS_TIMEOUT);
1819     }
1820 
1821     OrderAccess::fence();
1822 
1823     assert(owner_raw() != owner_for(current), "invariant");
1824     ObjectWaiter::TStates v = node.TState;
1825     if (v == ObjectWaiter::TS_RUN) {
1826       enter(current);
1827     } else {
1828       guarantee(v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant");
1829       ReenterI(current, &node);
1830       node.wait_reenter_end(this);
1831     }
1832 
1833     // current has reacquired the lock.
1834     // Lifecycle - the node representing current must not appear on any queues.
1835     // Node is about to go out-of-scope, but even if it were immortal we wouldn't
1836     // want residual elements associated with this thread left on any lists.
1837     guarantee(node.TState == ObjectWaiter::TS_RUN, "invariant");
1838     assert(owner_raw() == owner_for(current), "invariant");
1839     assert(_succ != current, "invariant");
1840   } // OSThreadWaitState()
1841 
1842   current->set_current_waiting_monitor(nullptr);
1843 
1844   guarantee(_recursions == 0, "invariant");
1845   int relock_count = JvmtiDeferredUpdates::get_and_reset_relock_count_after_wait(current);
1846   _recursions =   save          // restore the old recursion count
1847                 + relock_count; //  increased by the deferred relock count
1848   current->inc_held_monitor_count(relock_count); // Deopt never entered these counts.
1849   _waiters--;             // decrement the number of waiters
1850 
1851   // Verify a few postconditions
1852   assert(owner_raw() == owner_for(current), "invariant");
1853   assert(_succ != current, "invariant");
1854   assert_mark_word_consistency();
1855 
1856   // check if the notification happened
1857   if (!WasNotified) {
1858     // no, it could be timeout or Thread.interrupt() or both
1859     // check for interrupt event, otherwise it is timeout
1860     if (interruptible && current->is_interrupted(true) && !HAS_PENDING_EXCEPTION) {
1861       THROW(vmSymbols::java_lang_InterruptedException());
1862     }
1863   }
1864 
1865   // NOTE: Spurious wake up will be consider as timeout.
1866   // Monitor notify has precedence over thread interrupt.
1867 }
1868 
1869 // Consider:
1870 // If the lock is cool (cxq == null && succ == null) and we're on an MP system
1871 // then instead of transferring a thread from the WaitSet to the EntryList
1872 // we might just dequeue a thread from the WaitSet and directly unpark() it.
1873 
1874 void ObjectMonitor::INotify(JavaThread* current) {
1875   Thread::SpinAcquire(&_WaitSetLock, "WaitSet - notify");
1876   ObjectWaiter* iterator = DequeueWaiter();
1877   if (iterator != nullptr) {
1878     guarantee(iterator->TState == ObjectWaiter::TS_WAIT, "invariant");
1879     guarantee(!iterator->_notified, "invariant");
1880     // Disposition - what might we do with iterator ?
1881     // a.  add it directly to the EntryList - either tail (policy == 1)
1882     //     or head (policy == 0).
1883     // b.  push it onto the front of the _cxq (policy == 2).
1884     // For now we use (b).
1885 
1886     if (iterator->is_vthread()) {
1887       oop vthread = iterator->vthread();
1888       java_lang_VirtualThread::set_notified(vthread, true);
1889       int old_state = java_lang_VirtualThread::state(vthread);
1890       // If state is not WAIT/TIMED_WAIT then target could still be on
1891       // unmount transition, or wait could have already timed-out or target
1892       // could have been interrupted. In the first case, the target itself
1893       // will set the state to BLOCKED at the end of the unmount transition.
1894       // In the other cases the target would have been already unblocked so
1895       // there is nothing to do.
1896       if (old_state == java_lang_VirtualThread::WAIT ||
1897           old_state == java_lang_VirtualThread::TIMED_WAIT) {
1898         java_lang_VirtualThread::cmpxchg_state(vthread, old_state, java_lang_VirtualThread::BLOCKED);
1899       }
1900     }
1901 
1902     iterator->TState = ObjectWaiter::TS_ENTER;
1903 
1904     iterator->_notified = true;
1905     iterator->_notifier_tid = JFR_THREAD_ID(current);
1906 
1907     ObjectWaiter* list = _EntryList;
1908     if (list != nullptr) {
1909       assert(list->_prev == nullptr, "invariant");
1910       assert(list->TState == ObjectWaiter::TS_ENTER, "invariant");
1911       assert(list != iterator, "invariant");
1912     }
1913 
1914     // prepend to cxq
1915     if (list == nullptr) {
1916       iterator->_next = iterator->_prev = nullptr;
1917       _EntryList = iterator;
1918     } else {
1919       iterator->TState = ObjectWaiter::TS_CXQ;
1920       for (;;) {
1921         ObjectWaiter* front = _cxq;
1922         iterator->_next = front;
1923         if (Atomic::cmpxchg(&_cxq, front, iterator) == front) {
1924           break;
1925         }
1926       }
1927     }
1928 
1929     // _WaitSetLock protects the wait queue, not the EntryList.  We could
1930     // move the add-to-EntryList operation, above, outside the critical section
1931     // protected by _WaitSetLock.  In practice that's not useful.  With the
1932     // exception of  wait() timeouts and interrupts the monitor owner
1933     // is the only thread that grabs _WaitSetLock.  There's almost no contention
1934     // on _WaitSetLock so it's not profitable to reduce the length of the
1935     // critical section.
1936     if (!iterator->is_vthread()) {
1937       iterator->wait_reenter_begin(this);
1938     }
1939   }
1940   Thread::SpinRelease(&_WaitSetLock);
1941 }
1942 
1943 // Consider: a not-uncommon synchronization bug is to use notify() when
1944 // notifyAll() is more appropriate, potentially resulting in stranded
1945 // threads; this is one example of a lost wakeup. A useful diagnostic
1946 // option is to force all notify() operations to behave as notifyAll().
1947 //
1948 // Note: We can also detect many such problems with a "minimum wait".
1949 // When the "minimum wait" is set to a small non-zero timeout value
1950 // and the program does not hang whereas it did absent "minimum wait",
1951 // that suggests a lost wakeup bug.
1952 
1953 void ObjectMonitor::notify(TRAPS) {
1954   JavaThread* current = THREAD;
1955   CHECK_OWNER();  // Throws IMSE if not owner.
1956   if (_WaitSet == nullptr) {
1957     return;
1958   }
1959   DTRACE_MONITOR_PROBE(notify, this, object(), current);
1960   INotify(current);
1961   OM_PERFDATA_OP(Notifications, inc(1));
1962 }
1963 
1964 
1965 // The current implementation of notifyAll() transfers the waiters one-at-a-time
1966 // from the waitset to the EntryList. This could be done more efficiently with a
1967 // single bulk transfer but in practice it's not time-critical. Beware too,
1968 // that in prepend-mode we invert the order of the waiters. Let's say that the
1969 // waitset is "ABCD" and the EntryList is "XYZ". After a notifyAll() in prepend
1970 // mode the waitset will be empty and the EntryList will be "DCBAXYZ".
1971 
1972 void ObjectMonitor::notifyAll(TRAPS) {
1973   JavaThread* current = THREAD;
1974   CHECK_OWNER();  // Throws IMSE if not owner.
1975   if (_WaitSet == nullptr) {
1976     return;
1977   }
1978 
1979   DTRACE_MONITOR_PROBE(notifyAll, this, object(), current);
1980   int tally = 0;
1981   while (_WaitSet != nullptr) {
1982     tally++;
1983     INotify(current);
1984   }
1985 
1986   OM_PERFDATA_OP(Notifications, inc(tally));
1987 }
1988 
1989 void ObjectMonitor::VThreadWait(JavaThread* current, jlong millis) {
1990   oop vthread = current->vthread();
1991   ObjectWaiter* node = new ObjectWaiter(vthread, this);
1992   node->_is_wait = true;
1993   node->TState = ObjectWaiter::TS_WAIT;
1994   java_lang_VirtualThread::set_notified(vthread, false);  // Reset notified flag
1995 
1996   // Enter the waiting queue, which is a circular doubly linked list in this case
1997   // but it could be a priority queue or any data structure.
1998   // _WaitSetLock protects the wait queue.  Normally the wait queue is accessed only
1999   // by the owner of the monitor *except* in the case where park()
2000   // returns because of a timeout or interrupt.  Contention is exceptionally rare
2001   // so we use a simple spin-lock instead of a heavier-weight blocking lock.
2002 
2003   Thread::SpinAcquire(&_WaitSetLock, "WaitSet - add");
2004   AddWaiter(node);
2005   Thread::SpinRelease(&_WaitSetLock);
2006 
2007   node->_recursions = _recursions;   // record the old recursion count
2008   _recursions = 0;                   // set the recursion level to be 1
2009   _waiters++;                        // increment the number of waiters
2010   exit(current);                     // exit the monitor
2011   guarantee(owner_raw() != owner_for(current), "invariant");
2012 
2013   assert(java_lang_VirtualThread::state(vthread) == java_lang_VirtualThread::RUNNING, "wrong state for vthread");
2014   java_lang_VirtualThread::set_state(vthread, millis == 0 ? java_lang_VirtualThread::WAITING : java_lang_VirtualThread::TIMED_WAITING);
2015   java_lang_VirtualThread::set_waitTimeout(vthread, millis);
2016 
2017   // Save the ObjectWaiter* in the chunk since we will need it
2018   // when resuming execution.
2019   oop cont = java_lang_VirtualThread::continuation(vthread);
2020   stackChunkOop chunk  = jdk_internal_vm_Continuation::tail(cont);
2021   chunk->set_object_waiter(node);
2022 }
2023 
2024 bool ObjectMonitor::VThreadWaitReenter(JavaThread* current, ObjectWaiter* node, ContinuationWrapper& cont) {
2025   // First time we run after being preempted on Object.wait().
2026   // We need to check if we were interrupted or wait() timed-out
2027   // and in that case remove ourselves from the _WaitSet queue.
2028   if (node->TState == ObjectWaiter::TS_WAIT) {
2029     Thread::SpinAcquire(&_WaitSetLock, "WaitSet - unlink");
2030     if (node->TState == ObjectWaiter::TS_WAIT) {
2031       DequeueSpecificWaiter(node);       // unlink from WaitSet
2032       assert(!node->_notified, "invariant");
2033       node->TState = ObjectWaiter::TS_RUN;
2034     }
2035     Thread::SpinRelease(&_WaitSetLock);
2036   }
2037 
2038   ObjectWaiter::TStates state = node->TState;
2039   bool was_notified = state == ObjectWaiter::TS_ENTER || state == ObjectWaiter::TS_CXQ;
2040   assert(was_notified || state == ObjectWaiter::TS_RUN, "");
2041 
2042   // save it so that once we re-acquire the monitor we know if we need to throw IE.
2043   node->_interrupted = !was_notified && current->is_interrupted(false);
2044 
2045   EventJavaMonitorWait event;
2046   if (event.should_commit() || JvmtiExport::should_post_monitor_waited()) {
2047     vthread_monitor_waited_event(current, node, cont, &event, !was_notified && !node->_interrupted);
2048   }
2049 
2050   node->_at_reenter = true;
2051   assert(owner_raw() != owner_for(current), "invariant");
2052 
2053   if (!was_notified) {
2054     bool acquired = VThreadMonitorEnter(current, node);
2055     if (acquired) {
2056       guarantee(_recursions == 0, "invariant");
2057       _recursions = node->_recursions;   // restore the old recursion count
2058       _waiters--;                        // decrement the number of waiters
2059 
2060       if (node->_interrupted) {
2061         // We will throw at thaw end after finishing the mount transition.
2062         current->set_pending_interrupted_exception(true);
2063       }
2064 
2065       delete node;
2066       stackChunkOop chunk  = cont.tail();
2067       chunk->set_object_waiter(nullptr);
2068       return true;
2069     }
2070   } else {
2071     // Already moved to _cxq or _EntryList by notifier, so just add to contentions.
2072     add_to_contentions(1);
2073   }
2074   return false;
2075 }
2076 
2077 // -----------------------------------------------------------------------------
2078 // Adaptive Spinning Support
2079 //
2080 // Adaptive spin-then-block - rational spinning
2081 //
2082 // Note that we spin "globally" on _owner with a classic SMP-polite TATAS
2083 // algorithm.  On high order SMP systems it would be better to start with
2084 // a brief global spin and then revert to spinning locally.  In the spirit of MCS/CLH,
2085 // a contending thread could enqueue itself on the cxq and then spin locally
2086 // on a thread-specific variable such as its ParkEvent._Event flag.
2087 // That's left as an exercise for the reader.  Note that global spinning is
2088 // not problematic on Niagara, as the L2 cache serves the interconnect and
2089 // has both low latency and massive bandwidth.
2090 //
2091 // Broadly, we can fix the spin frequency -- that is, the % of contended lock
2092 // acquisition attempts where we opt to spin --  at 100% and vary the spin count
2093 // (duration) or we can fix the count at approximately the duration of
2094 // a context switch and vary the frequency.   Of course we could also
2095 // vary both satisfying K == Frequency * Duration, where K is adaptive by monitor.
2096 // For a description of 'Adaptive spin-then-block mutual exclusion in
2097 // multi-threaded processing,' see U.S. Pat. No. 8046758.
2098 //
2099 // This implementation varies the duration "D", where D varies with
2100 // the success rate of recent spin attempts. (D is capped at approximately
2101 // length of a round-trip context switch).  The success rate for recent
2102 // spin attempts is a good predictor of the success rate of future spin
2103 // attempts.  The mechanism adapts automatically to varying critical
2104 // section length (lock modality), system load and degree of parallelism.
2105 // D is maintained per-monitor in _SpinDuration and is initialized
2106 // optimistically.  Spin frequency is fixed at 100%.
2107 //
2108 // Note that _SpinDuration is volatile, but we update it without locks
2109 // or atomics.  The code is designed so that _SpinDuration stays within
2110 // a reasonable range even in the presence of races.  The arithmetic
2111 // operations on _SpinDuration are closed over the domain of legal values,
2112 // so at worst a race will install and older but still legal value.
2113 // At the very worst this introduces some apparent non-determinism.
2114 // We might spin when we shouldn't or vice-versa, but since the spin
2115 // count are relatively short, even in the worst case, the effect is harmless.
2116 //
2117 // Care must be taken that a low "D" value does not become an
2118 // an absorbing state.  Transient spinning failures -- when spinning
2119 // is overall profitable -- should not cause the system to converge
2120 // on low "D" values.  We want spinning to be stable and predictable
2121 // and fairly responsive to change and at the same time we don't want
2122 // it to oscillate, become metastable, be "too" non-deterministic,
2123 // or converge on or enter undesirable stable absorbing states.
2124 //
2125 // We implement a feedback-based control system -- using past behavior
2126 // to predict future behavior.  We face two issues: (a) if the
2127 // input signal is random then the spin predictor won't provide optimal
2128 // results, and (b) if the signal frequency is too high then the control
2129 // system, which has some natural response lag, will "chase" the signal.
2130 // (b) can arise from multimodal lock hold times.  Transient preemption
2131 // can also result in apparent bimodal lock hold times.
2132 // Although sub-optimal, neither condition is particularly harmful, as
2133 // in the worst-case we'll spin when we shouldn't or vice-versa.
2134 // The maximum spin duration is rather short so the failure modes aren't bad.
2135 // To be conservative, I've tuned the gain in system to bias toward
2136 // _not spinning.  Relatedly, the system can sometimes enter a mode where it
2137 // "rings" or oscillates between spinning and not spinning.  This happens
2138 // when spinning is just on the cusp of profitability, however, so the
2139 // situation is not dire.  The state is benign -- there's no need to add
2140 // hysteresis control to damp the transition rate between spinning and
2141 // not spinning.
2142 
2143 int ObjectMonitor::Knob_SpinLimit    = 5000;   // derived by an external tool
2144 
2145 static int Knob_Bonus               = 100;     // spin success bonus
2146 static int Knob_Penalty             = 200;     // spin failure penalty
2147 static int Knob_Poverty             = 1000;
2148 static int Knob_FixedSpin           = 0;
2149 static int Knob_PreSpin             = 10;      // 20-100 likely better, but it's not better in my testing.
2150 
2151 inline static int adjust_up(int spin_duration) {
2152   int x = spin_duration;
2153   if (x < ObjectMonitor::Knob_SpinLimit) {
2154     if (x < Knob_Poverty) {
2155       x = Knob_Poverty;
2156     }
2157     return x + Knob_Bonus;
2158   } else {
2159     return spin_duration;
2160   }
2161 }
2162 
2163 inline static int adjust_down(int spin_duration) {
2164   // TODO: Use an AIMD-like policy to adjust _SpinDuration.
2165   // AIMD is globally stable.
2166   int x = spin_duration;
2167   if (x > 0) {
2168     // Consider an AIMD scheme like: x -= (x >> 3) + 100
2169     // This is globally sample and tends to damp the response.
2170     x -= Knob_Penalty;
2171     if (x < 0) { x = 0; }
2172     return x;
2173   } else {
2174     return spin_duration;
2175   }
2176 }
2177 
2178 bool ObjectMonitor::short_fixed_spin(JavaThread* current, int spin_count, bool adapt) {
2179   for (int ctr = 0; ctr < spin_count; ctr++) {
2180     TryLockResult status = TryLock(current);
2181     if (status == TryLockResult::Success) {
2182       if (adapt) {
2183         _SpinDuration = adjust_up(_SpinDuration);
2184       }
2185       return true;
2186     } else if (status == TryLockResult::Interference) {
2187       break;
2188     }
2189     SpinPause();
2190   }
2191   return false;
2192 }
2193 
2194 // Spinning: Fixed frequency (100%), vary duration
2195 bool ObjectMonitor::TrySpin(JavaThread* current) {
2196 
2197   // Dumb, brutal spin.  Good for comparative measurements against adaptive spinning.
2198   int knob_fixed_spin = Knob_FixedSpin;  // 0 (don't spin: default), 2000 good test
2199   if (knob_fixed_spin > 0) {
2200     return short_fixed_spin(current, knob_fixed_spin, false);
2201   }
2202 
2203   // Admission control - verify preconditions for spinning
2204   //
2205   // We always spin a little bit, just to prevent _SpinDuration == 0 from
2206   // becoming an absorbing state.  Put another way, we spin briefly to
2207   // sample, just in case the system load, parallelism, contention, or lock
2208   // modality changed.
2209 
2210   int knob_pre_spin = Knob_PreSpin; // 10 (default), 100, 1000 or 2000
2211   if (short_fixed_spin(current, knob_pre_spin, true)) {
2212     return true;
2213   }
2214 
2215   //
2216   // Consider the following alternative:
2217   // Periodically set _SpinDuration = _SpinLimit and try a long/full
2218   // spin attempt.  "Periodically" might mean after a tally of
2219   // the # of failed spin attempts (or iterations) reaches some threshold.
2220   // This takes us into the realm of 1-out-of-N spinning, where we
2221   // hold the duration constant but vary the frequency.
2222 
2223   int ctr = _SpinDuration;
2224   if (ctr <= 0) return false;
2225 
2226   // We're good to spin ... spin ingress.
2227   // CONSIDER: use Prefetch::write() to avoid RTS->RTO upgrades
2228   // when preparing to LD...CAS _owner, etc and the CAS is likely
2229   // to succeed.
2230   if (_succ == nullptr) {
2231     _succ = current;
2232   }
2233   void* prv = nullptr;
2234 
2235   // There are three ways to exit the following loop:
2236   // 1.  A successful spin where this thread has acquired the lock.
2237   // 2.  Spin failure with prejudice
2238   // 3.  Spin failure without prejudice
2239 
2240   while (--ctr >= 0) {
2241 
2242     // Periodic polling -- Check for pending GC
2243     // Threads may spin while they're unsafe.
2244     // We don't want spinning threads to delay the JVM from reaching
2245     // a stop-the-world safepoint or to steal cycles from GC.
2246     // If we detect a pending safepoint we abort in order that
2247     // (a) this thread, if unsafe, doesn't delay the safepoint, and (b)
2248     // this thread, if safe, doesn't steal cycles from GC.
2249     // This is in keeping with the "no loitering in runtime" rule.
2250     // We periodically check to see if there's a safepoint pending.
2251     if ((ctr & 0xFF) == 0) {
2252       // Can't call SafepointMechanism::should_process() since that
2253       // might update the poll values and we could be in a thread_blocked
2254       // state here which is not allowed so just check the poll.
2255       if (SafepointMechanism::local_poll_armed(current)) {
2256         break;
2257       }
2258       SpinPause();
2259     }
2260 
2261     // Probe _owner with TATAS
2262     // If this thread observes the monitor transition or flicker
2263     // from locked to unlocked to locked, then the odds that this
2264     // thread will acquire the lock in this spin attempt go down
2265     // considerably.  The same argument applies if the CAS fails
2266     // or if we observe _owner change from one non-null value to
2267     // another non-null value.   In such cases we might abort
2268     // the spin without prejudice or apply a "penalty" to the
2269     // spin count-down variable "ctr", reducing it by 100, say.
2270 
2271     void* ox = owner_raw();
2272     if (ox == nullptr) {
2273       ox = try_set_owner_from(nullptr, current);
2274       if (ox == nullptr) {
2275         // The CAS succeeded -- this thread acquired ownership
2276         // Take care of some bookkeeping to exit spin state.
2277         if (_succ == current) {
2278           _succ = nullptr;
2279         }
2280 
2281         // Increase _SpinDuration :
2282         // The spin was successful (profitable) so we tend toward
2283         // longer spin attempts in the future.
2284         // CONSIDER: factor "ctr" into the _SpinDuration adjustment.
2285         // If we acquired the lock early in the spin cycle it
2286         // makes sense to increase _SpinDuration proportionally.
2287         // Note that we don't clamp SpinDuration precisely at SpinLimit.
2288         _SpinDuration = adjust_up(_SpinDuration);
2289         return true;
2290       }
2291 
2292       // The CAS failed ... we can take any of the following actions:
2293       // * penalize: ctr -= CASPenalty
2294       // * exit spin with prejudice -- abort without adapting spinner
2295       // * exit spin without prejudice.
2296       // * Since CAS is high-latency, retry again immediately.
2297       break;
2298     }
2299 
2300     // Did lock ownership change hands ?
2301     if (ox != prv && prv != nullptr) {
2302       break;
2303     }
2304     prv = ox;
2305 
2306     if (_succ == nullptr) {
2307       _succ = current;
2308     }
2309   }
2310 
2311   // Spin failed with prejudice -- reduce _SpinDuration.
2312   if (ctr < 0) {
2313     _SpinDuration = adjust_down(_SpinDuration);
2314   }
2315 
2316   if (_succ == current) {
2317     _succ = nullptr;
2318     // Invariant: after setting succ=null a contending thread
2319     // must recheck-retry _owner before parking.  This usually happens
2320     // in the normal usage of TrySpin(), but it's safest
2321     // to make TrySpin() as foolproof as possible.
2322     OrderAccess::fence();
2323     if (TryLock(current) == TryLockResult::Success) {
2324       return true;
2325     }
2326   }
2327 
2328   return false;
2329 }
2330 
2331 
2332 // -----------------------------------------------------------------------------
2333 // WaitSet management ...
2334 
2335 ObjectWaiter::ObjectWaiter(JavaThread* current) {
2336   _next     = nullptr;
2337   _prev     = nullptr;
2338   _thread   = current;
2339   _monitor  = nullptr;
2340   _notifier_tid = 0;
2341   _recursions = 0;
2342   TState    = TS_RUN;
2343   _notified = false;
2344   _is_wait  = false;
2345   _at_reenter = false;
2346   _interrupted = false;
2347   _active   = false;
2348 }
2349 
2350 ObjectWaiter::ObjectWaiter(oop vthread, ObjectMonitor* mon) : ObjectWaiter(nullptr) {
2351   assert(oopDesc::is_oop(vthread), "");
2352   _vthread = OopHandle(JavaThread::thread_oop_storage(), vthread);
2353   _monitor = mon;
2354 }
2355 
2356 ObjectWaiter::~ObjectWaiter() {
2357   if (is_vthread()) {
2358     assert(vthread() != nullptr, "");
2359     _vthread.release(JavaThread::thread_oop_storage());
2360   }
2361 }
2362 
2363 oop ObjectWaiter::vthread() {
2364   return _vthread.resolve();
2365 }
2366 
2367 void ObjectWaiter::wait_reenter_begin(ObjectMonitor * const mon) {
2368   _active = JavaThreadBlockedOnMonitorEnterState::wait_reenter_begin(_thread, mon);
2369 }
2370 
2371 void ObjectWaiter::wait_reenter_end(ObjectMonitor * const mon) {
2372   JavaThreadBlockedOnMonitorEnterState::wait_reenter_end(_thread, _active);
2373 }
2374 
2375 inline void ObjectMonitor::AddWaiter(ObjectWaiter* node) {
2376   assert(node != nullptr, "should not add null node");
2377   assert(node->_prev == nullptr, "node already in list");
2378   assert(node->_next == nullptr, "node already in list");
2379   // put node at end of queue (circular doubly linked list)
2380   if (_WaitSet == nullptr) {
2381     _WaitSet = node;
2382     node->_prev = node;
2383     node->_next = node;
2384   } else {
2385     ObjectWaiter* head = _WaitSet;
2386     ObjectWaiter* tail = head->_prev;
2387     assert(tail->_next == head, "invariant check");
2388     tail->_next = node;
2389     head->_prev = node;
2390     node->_next = head;
2391     node->_prev = tail;
2392   }
2393 }
2394 
2395 inline ObjectWaiter* ObjectMonitor::DequeueWaiter() {
2396   // dequeue the very first waiter
2397   ObjectWaiter* waiter = _WaitSet;
2398   if (waiter) {
2399     DequeueSpecificWaiter(waiter);
2400   }
2401   return waiter;
2402 }
2403 
2404 inline void ObjectMonitor::DequeueSpecificWaiter(ObjectWaiter* node) {
2405   assert(node != nullptr, "should not dequeue nullptr node");
2406   assert(node->_prev != nullptr, "node already removed from list");
2407   assert(node->_next != nullptr, "node already removed from list");
2408   // when the waiter has woken up because of interrupt,
2409   // timeout or other spurious wake-up, dequeue the
2410   // waiter from waiting list
2411   ObjectWaiter* next = node->_next;
2412   if (next == node) {
2413     assert(node->_prev == node, "invariant check");
2414     _WaitSet = nullptr;
2415   } else {
2416     ObjectWaiter* prev = node->_prev;
2417     assert(prev->_next == node, "invariant check");
2418     assert(next->_prev == node, "invariant check");
2419     next->_prev = prev;
2420     prev->_next = next;
2421     if (_WaitSet == node) {
2422       _WaitSet = next;
2423     }
2424   }
2425   node->_next = nullptr;
2426   node->_prev = nullptr;
2427 }
2428 
2429 // -----------------------------------------------------------------------------
2430 // PerfData support
2431 PerfCounter * ObjectMonitor::_sync_ContendedLockAttempts       = nullptr;
2432 PerfCounter * ObjectMonitor::_sync_FutileWakeups               = nullptr;
2433 PerfCounter * ObjectMonitor::_sync_Parks                       = nullptr;
2434 PerfCounter * ObjectMonitor::_sync_Notifications               = nullptr;
2435 PerfCounter * ObjectMonitor::_sync_Inflations                  = nullptr;
2436 PerfCounter * ObjectMonitor::_sync_Deflations                  = nullptr;
2437 PerfLongVariable * ObjectMonitor::_sync_MonExtant              = nullptr;
2438 
2439 // One-shot global initialization for the sync subsystem.
2440 // We could also defer initialization and initialize on-demand
2441 // the first time we call ObjectSynchronizer::inflate().
2442 // Initialization would be protected - like so many things - by
2443 // the MonitorCache_lock.
2444 
2445 void ObjectMonitor::Initialize() {
2446   assert(!InitDone, "invariant");
2447 
2448   if (!os::is_MP()) {
2449     Knob_SpinLimit = 0;
2450     Knob_PreSpin   = 0;
2451     Knob_FixedSpin = -1;
2452   }
2453 
2454   if (UsePerfData) {
2455     EXCEPTION_MARK;
2456 #define NEWPERFCOUNTER(n)                                                \
2457   {                                                                      \
2458     n = PerfDataManager::create_counter(SUN_RT, #n, PerfData::U_Events,  \
2459                                         CHECK);                          \
2460   }
2461 #define NEWPERFVARIABLE(n)                                                \
2462   {                                                                       \
2463     n = PerfDataManager::create_variable(SUN_RT, #n, PerfData::U_Events,  \
2464                                          CHECK);                          \
2465   }
2466     NEWPERFCOUNTER(_sync_Inflations);
2467     NEWPERFCOUNTER(_sync_Deflations);
2468     NEWPERFCOUNTER(_sync_ContendedLockAttempts);
2469     NEWPERFCOUNTER(_sync_FutileWakeups);
2470     NEWPERFCOUNTER(_sync_Parks);
2471     NEWPERFCOUNTER(_sync_Notifications);
2472     NEWPERFVARIABLE(_sync_MonExtant);
2473 #undef NEWPERFCOUNTER
2474 #undef NEWPERFVARIABLE
2475   }
2476 
2477   _oop_storage = OopStorageSet::create_weak("ObjectSynchronizer Weak", mtSynchronizer);
2478 
2479   DEBUG_ONLY(InitDone = true;)
2480 }
2481 
2482 void ObjectMonitor::Initialize2() {
2483   _vthread_cxq_head = OopHandle(JavaThread::thread_oop_storage(), nullptr);
2484   _vthread_unparker_ParkEvent = ParkEvent::Allocate(nullptr);
2485 }
2486 
2487 void ObjectMonitor::print_on(outputStream* st) const {
2488   // The minimal things to print for markWord printing, more can be added for debugging and logging.
2489   st->print("{contentions=0x%08x,waiters=0x%08x"
2490             ",recursions=" INTX_FORMAT ",owner=" INTPTR_FORMAT "}",
2491             contentions(), waiters(), recursions(),
2492             p2i(owner()));
2493 }
2494 void ObjectMonitor::print() const { print_on(tty); }
2495 
2496 #ifdef ASSERT
2497 // Print the ObjectMonitor like a debugger would:
2498 //
2499 // (ObjectMonitor) 0x00007fdfb6012e40 = {
2500 //   _metadata = 0x0000000000000001
2501 //   _object = 0x000000070ff45fd0
2502 //   _pad_buf0 = {
2503 //     [0] = '\0'
2504 //     ...
2505 //     [43] = '\0'
2506 //   }
2507 //   _owner = 0x0000000000000000
2508 //   _previous_owner_tid = 0
2509 //   _pad_buf1 = {
2510 //     [0] = '\0'
2511 //     ...
2512 //     [47] = '\0'
2513 //   }
2514 //   _next_om = 0x0000000000000000
2515 //   _recursions = 0
2516 //   _EntryList = 0x0000000000000000
2517 //   _cxq = 0x0000000000000000
2518 //   _succ = 0x0000000000000000
2519 //   _SpinDuration = 5000
2520 //   _contentions = 0
2521 //   _WaitSet = 0x0000700009756248
2522 //   _waiters = 1
2523 //   _WaitSetLock = 0
2524 // }
2525 //
2526 void ObjectMonitor::print_debug_style_on(outputStream* st) const {
2527   st->print_cr("(ObjectMonitor*) " INTPTR_FORMAT " = {", p2i(this));
2528   st->print_cr("  _metadata = " INTPTR_FORMAT, _metadata);
2529   st->print_cr("  _object = " INTPTR_FORMAT, p2i(object_peek()));
2530   st->print_cr("  _pad_buf0 = {");
2531   st->print_cr("    [0] = '\\0'");
2532   st->print_cr("    ...");
2533   st->print_cr("    [%d] = '\\0'", (int)sizeof(_pad_buf0) - 1);
2534   st->print_cr("  }");
2535   st->print_cr("  _owner = " INTPTR_FORMAT, p2i(owner_raw()));
2536   st->print_cr("  _previous_owner_tid = " UINT64_FORMAT, _previous_owner_tid);
2537   st->print_cr("  _pad_buf1 = {");
2538   st->print_cr("    [0] = '\\0'");
2539   st->print_cr("    ...");
2540   st->print_cr("    [%d] = '\\0'", (int)sizeof(_pad_buf1) - 1);
2541   st->print_cr("  }");
2542   st->print_cr("  _next_om = " INTPTR_FORMAT, p2i(next_om()));
2543   st->print_cr("  _recursions = " INTX_FORMAT, _recursions);
2544   st->print_cr("  _EntryList = " INTPTR_FORMAT, p2i(_EntryList));
2545   st->print_cr("  _cxq = " INTPTR_FORMAT, p2i(_cxq));
2546   st->print_cr("  _succ = " INTPTR_FORMAT, p2i(_succ));
2547   st->print_cr("  _SpinDuration = %d", _SpinDuration);
2548   st->print_cr("  _contentions = %d", contentions());
2549   st->print_cr("  _WaitSet = " INTPTR_FORMAT, p2i(_WaitSet));
2550   st->print_cr("  _waiters = %d", _waiters);
2551   st->print_cr("  _WaitSetLock = %d", _WaitSetLock);
2552   st->print_cr("}");
2553 }
2554 #endif