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