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