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