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