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