1 /*
   2  * Copyright (c) 1998, 2020, 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 "logging/log.hpp"
  28 #include "logging/logStream.hpp"
  29 #include "jfr/jfrEvents.hpp"
  30 #include "memory/allocation.inline.hpp"
  31 #include "memory/metaspaceShared.hpp"
  32 #include "memory/padded.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "memory/universe.hpp"
  35 #include "oops/markWord.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "runtime/atomic.hpp"
  38 #include "runtime/biasedLocking.hpp"
  39 #include "runtime/handles.inline.hpp"
  40 #include "runtime/handshake.hpp"
  41 #include "runtime/interfaceSupport.inline.hpp"
  42 #include "runtime/mutexLocker.hpp"
  43 #include "runtime/objectMonitor.hpp"
  44 #include "runtime/objectMonitor.inline.hpp"
  45 #include "runtime/osThread.hpp"
  46 #include "runtime/safepointMechanism.inline.hpp"
  47 #include "runtime/safepointVerifiers.hpp"
  48 #include "runtime/sharedRuntime.hpp"
  49 #include "runtime/stubRoutines.hpp"
  50 #include "runtime/synchronizer.hpp"
  51 #include "runtime/thread.inline.hpp"
  52 #include "runtime/timer.hpp"
  53 #include "runtime/vframe.hpp"
  54 #include "runtime/vmThread.hpp"
  55 #include "utilities/align.hpp"
  56 #include "utilities/dtrace.hpp"
  57 #include "utilities/events.hpp"
  58 #include "utilities/preserveException.hpp"
  59 
  60 // The "core" versions of monitor enter and exit reside in this file.
  61 // The interpreter and compilers contain specialized transliterated
  62 // variants of the enter-exit fast-path operations.  See i486.ad fast_lock(),
  63 // for instance.  If you make changes here, make sure to modify the
  64 // interpreter, and both C1 and C2 fast-path inline locking code emission.
  65 //
  66 // -----------------------------------------------------------------------------
  67 
  68 #ifdef DTRACE_ENABLED
  69 
  70 // Only bother with this argument setup if dtrace is available
  71 // TODO-FIXME: probes should not fire when caller is _blocked.  assert() accordingly.
  72 
  73 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread)                           \
  74   char* bytes = NULL;                                                      \
  75   int len = 0;                                                             \
  76   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
  77   Symbol* klassname = ((oop)(obj))->klass()->name();                       \
  78   if (klassname != NULL) {                                                 \
  79     bytes = (char*)klassname->bytes();                                     \
  80     len = klassname->utf8_length();                                        \
  81   }
  82 
  83 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis)            \
  84   {                                                                        \
  85     if (DTraceMonitorProbes) {                                             \
  86       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
  87       HOTSPOT_MONITOR_WAIT(jtid,                                           \
  88                            (uintptr_t)(monitor), bytes, len, (millis));    \
  89     }                                                                      \
  90   }
  91 
  92 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY
  93 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL
  94 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED
  95 
  96 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread)                  \
  97   {                                                                        \
  98     if (DTraceMonitorProbes) {                                             \
  99       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 100       HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */             \
 101                                     (uintptr_t)(monitor), bytes, len);     \
 102     }                                                                      \
 103   }
 104 
 105 #else //  ndef DTRACE_ENABLED
 106 
 107 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon)    {;}
 108 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon)          {;}
 109 
 110 #endif // ndef DTRACE_ENABLED
 111 
 112 // This exists only as a workaround of dtrace bug 6254741
 113 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
 114   DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
 115   return 0;
 116 }
 117 
 118 #define NINFLATIONLOCKS 256
 119 static volatile intptr_t gInflationLocks[NINFLATIONLOCKS];
 120 
 121 // global list of blocks of monitors
 122 PaddedObjectMonitor* ObjectSynchronizer::g_block_list = NULL;
 123 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false;
 124 bool volatile ObjectSynchronizer::_is_special_deflation_requested = false;
 125 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0;
 126 
 127 struct ObjectMonitorListGlobals {
 128   char         _pad_prefix[OM_CACHE_LINE_SIZE];
 129   // These are highly shared list related variables.
 130   // To avoid false-sharing they need to be the sole occupants of a cache line.
 131 
 132   // Global ObjectMonitor free list. Newly allocated and deflated
 133   // ObjectMonitors are prepended here.
 134   ObjectMonitor* _free_list;
 135   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(ObjectMonitor*));
 136 
 137   // Global ObjectMonitor in-use list. When a JavaThread is exiting,
 138   // ObjectMonitors on its per-thread in-use list are prepended here.
 139   ObjectMonitor* _in_use_list;
 140   DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(ObjectMonitor*));
 141 
 142   // Global ObjectMonitor wait list. Deflated ObjectMonitors wait on
 143   // this list until after a handshake or a safepoint for platforms
 144   // that don't support handshakes. After the handshake or safepoint,
 145   // the deflated ObjectMonitors are prepended to free_list.
 146   ObjectMonitor* _wait_list;
 147   DEFINE_PAD_MINUS_SIZE(3, OM_CACHE_LINE_SIZE, sizeof(ObjectMonitor*));
 148 
 149   int _free_count;    // # on free_list
 150   DEFINE_PAD_MINUS_SIZE(4, OM_CACHE_LINE_SIZE, sizeof(int));
 151 
 152   int _in_use_count;  // # on in_use_list
 153   DEFINE_PAD_MINUS_SIZE(5, OM_CACHE_LINE_SIZE, sizeof(int));
 154 
 155   int _population;    // # Extant -- in circulation
 156   DEFINE_PAD_MINUS_SIZE(6, OM_CACHE_LINE_SIZE, sizeof(int));
 157 
 158   int _wait_count;    // # on wait_list
 159   DEFINE_PAD_MINUS_SIZE(7, OM_CACHE_LINE_SIZE, sizeof(int));
 160 };
 161 static ObjectMonitorListGlobals om_list_globals;
 162 
 163 #define CHAINMARKER (cast_to_oop<intptr_t>(-1))
 164 
 165 
 166 // =====================> Spin-lock functions
 167 
 168 // ObjectMonitors are not lockable outside of this file. We use spin-locks
 169 // implemented using a bit in the _next_om field instead of the heavier
 170 // weight locking mechanisms for faster list management.
 171 
 172 #define OM_LOCK_BIT 0x1
 173 
 174 // Return true if the ObjectMonitor is locked.
 175 // Otherwise returns false.
 176 static bool is_locked(ObjectMonitor* om) {
 177   return ((intptr_t)om->next_om() & OM_LOCK_BIT) == OM_LOCK_BIT;
 178 }
 179 
 180 // Mark an ObjectMonitor* with OM_LOCK_BIT and return it.
 181 static ObjectMonitor* mark_om_ptr(ObjectMonitor* om) {
 182   return (ObjectMonitor*)((intptr_t)om | OM_LOCK_BIT);
 183 }
 184 
 185 // Return the unmarked next field in an ObjectMonitor. Note: the next
 186 // field may or may not have been marked with OM_LOCK_BIT originally.
 187 static ObjectMonitor* unmarked_next(ObjectMonitor* om) {
 188   return (ObjectMonitor*)((intptr_t)om->next_om() & ~OM_LOCK_BIT);
 189 }
 190 
 191 // Try to lock an ObjectMonitor. Returns true if locking was successful.
 192 // Otherwise returns false.
 193 static bool try_om_lock(ObjectMonitor* om) {
 194   // Get current next field without any OM_LOCK_BIT value.
 195   ObjectMonitor* next = unmarked_next(om);
 196   if (om->try_set_next_om(next, mark_om_ptr(next)) != next) {
 197     return false;  // Cannot lock the ObjectMonitor.
 198   }
 199   return true;
 200 }
 201 
 202 // Lock an ObjectMonitor.
 203 static void om_lock(ObjectMonitor* om) {
 204   while (true) {
 205     if (try_om_lock(om)) {
 206       return;
 207     }
 208   }
 209 }
 210 
 211 // Unlock an ObjectMonitor.
 212 static void om_unlock(ObjectMonitor* om) {
 213   ObjectMonitor* next = om->next_om();
 214   guarantee(((intptr_t)next & OM_LOCK_BIT) == OM_LOCK_BIT, "next=" INTPTR_FORMAT
 215             " must have OM_LOCK_BIT=%x set.", p2i(next), OM_LOCK_BIT);
 216 
 217   next = (ObjectMonitor*)((intptr_t)next & ~OM_LOCK_BIT);  // Clear OM_LOCK_BIT.
 218   om->set_next_om(next);
 219 }
 220 
 221 // Get the list head after locking it. Returns the list head or NULL
 222 // if the list is empty.
 223 static ObjectMonitor* get_list_head_locked(ObjectMonitor** list_p) {
 224   while (true) {
 225     ObjectMonitor* mid = Atomic::load(list_p);
 226     if (mid == NULL) {
 227       return NULL;  // The list is empty.
 228     }
 229     if (try_om_lock(mid)) {
 230       if (Atomic::load(list_p) != mid) {
 231         // The list head changed before we could lock it so we have to retry.
 232         om_unlock(mid);
 233         continue;
 234       }
 235       return mid;
 236     }
 237   }
 238 }
 239 
 240 #undef OM_LOCK_BIT
 241 
 242 
 243 // =====================> List Management functions
 244 
 245 // Prepend a list of ObjectMonitors to the specified *list_p. 'tail' is
 246 // the last ObjectMonitor in the list and there are 'count' on the list.
 247 // Also updates the specified *count_p.
 248 static void prepend_list_to_common(ObjectMonitor* list, ObjectMonitor* tail,
 249                                    int count, ObjectMonitor** list_p,
 250                                    int* count_p) {
 251   while (true) {
 252     ObjectMonitor* cur = Atomic::load(list_p);
 253     // Prepend list to *list_p.
 254     if (!try_om_lock(tail)) {
 255       // Failed to lock tail due to a list walker so try it all again.
 256       continue;
 257     }
 258     tail->set_next_om(cur);  // tail now points to cur (and unlocks tail)
 259     if (cur == NULL) {
 260       // No potential race with takers or other prependers since
 261       // *list_p is empty.
 262       if (Atomic::cmpxchg(list_p, cur, list) == cur) {
 263         // Successfully switched *list_p to the list value.
 264         Atomic::add(count_p, count);
 265         break;
 266       }
 267       // Implied else: try it all again
 268     } else {
 269       if (!try_om_lock(cur)) {
 270         continue;  // failed to lock cur so try it all again
 271       }
 272       // We locked cur so try to switch *list_p to the list value.
 273       if (Atomic::cmpxchg(list_p, cur, list) != cur) {
 274         // The list head has changed so unlock cur and try again:
 275         om_unlock(cur);
 276         continue;
 277       }
 278       Atomic::add(count_p, count);
 279       om_unlock(cur);
 280       break;
 281     }
 282   }
 283 }
 284 
 285 // Prepend a newly allocated block of ObjectMonitors to g_block_list and
 286 // om_list_globals._free_list. Also updates om_list_globals._population
 287 // and om_list_globals._free_count.
 288 void ObjectSynchronizer::prepend_block_to_lists(PaddedObjectMonitor* new_blk) {
 289   // First we handle g_block_list:
 290   while (true) {
 291     PaddedObjectMonitor* cur = Atomic::load(&g_block_list);
 292     // Prepend new_blk to g_block_list. The first ObjectMonitor in
 293     // a block is reserved for use as linkage to the next block.
 294     new_blk[0].set_next_om(cur);
 295     if (Atomic::cmpxchg(&g_block_list, cur, new_blk) == cur) {
 296       // Successfully switched g_block_list to the new_blk value.
 297       Atomic::add(&om_list_globals._population, _BLOCKSIZE - 1);
 298       break;
 299     }
 300     // Implied else: try it all again
 301   }
 302 
 303   // Second we handle om_list_globals._free_list:
 304   prepend_list_to_common(new_blk + 1, &new_blk[_BLOCKSIZE - 1], _BLOCKSIZE - 1,
 305                          &om_list_globals._free_list, &om_list_globals._free_count);
 306 }
 307 
 308 // Prepend a list of ObjectMonitors to om_list_globals._free_list.
 309 // 'tail' is the last ObjectMonitor in the list and there are 'count'
 310 // on the list. Also updates om_list_globals._free_count.
 311 static void prepend_list_to_global_free_list(ObjectMonitor* list,
 312                                              ObjectMonitor* tail, int count) {
 313   prepend_list_to_common(list, tail, count, &om_list_globals._free_list,
 314                          &om_list_globals._free_count);
 315 }
 316 
 317 // Prepend a list of ObjectMonitors to om_list_globals._wait_list.
 318 // 'tail' is the last ObjectMonitor in the list and there are 'count'
 319 // on the list. Also updates om_list_globals._wait_count.
 320 static void prepend_list_to_global_wait_list(ObjectMonitor* list,
 321                                              ObjectMonitor* tail, int count) {
 322   prepend_list_to_common(list, tail, count, &om_list_globals._wait_list,
 323                          &om_list_globals._wait_count);
 324 }
 325 
 326 // Prepend a list of ObjectMonitors to om_list_globals._in_use_list.
 327 // 'tail' is the last ObjectMonitor in the list and there are 'count'
 328 // on the list. Also updates om_list_globals._in_use_list.
 329 static void prepend_list_to_global_in_use_list(ObjectMonitor* list,
 330                                                ObjectMonitor* tail, int count) {
 331   prepend_list_to_common(list, tail, count, &om_list_globals._in_use_list,
 332                          &om_list_globals._in_use_count);
 333 }
 334 
 335 // Prepend an ObjectMonitor to the specified list. Also updates
 336 // the specified counter.
 337 static void prepend_to_common(ObjectMonitor* m, ObjectMonitor** list_p,
 338                               int* count_p) {
 339   while (true) {
 340     om_lock(m);  // Lock m so we can safely update its next field.
 341     ObjectMonitor* cur = NULL;
 342     // Lock the list head to guard against races with a list walker
 343     // or async deflater thread (which only races in om_in_use_list):
 344     if ((cur = get_list_head_locked(list_p)) != NULL) {
 345       // List head is now locked so we can safely switch it.
 346       m->set_next_om(cur);  // m now points to cur (and unlocks m)
 347       Atomic::store(list_p, m);  // Switch list head to unlocked m.
 348       om_unlock(cur);
 349       break;
 350     }
 351     // The list is empty so try to set the list head.
 352     assert(cur == NULL, "cur must be NULL: cur=" INTPTR_FORMAT, p2i(cur));
 353     m->set_next_om(cur);  // m now points to NULL (and unlocks m)
 354     if (Atomic::cmpxchg(list_p, cur, m) == cur) {
 355       // List head is now unlocked m.
 356       break;
 357     }
 358     // Implied else: try it all again
 359   }
 360   Atomic::inc(count_p);
 361 }
 362 
 363 // Prepend an ObjectMonitor to a per-thread om_free_list.
 364 // Also updates the per-thread om_free_count.
 365 static void prepend_to_om_free_list(Thread* self, ObjectMonitor* m) {
 366   prepend_to_common(m, &self->om_free_list, &self->om_free_count);
 367 }
 368 
 369 // Prepend an ObjectMonitor to a per-thread om_in_use_list.
 370 // Also updates the per-thread om_in_use_count.
 371 static void prepend_to_om_in_use_list(Thread* self, ObjectMonitor* m) {
 372   prepend_to_common(m, &self->om_in_use_list, &self->om_in_use_count);
 373 }
 374 
 375 // Take an ObjectMonitor from the start of the specified list. Also
 376 // decrements the specified counter. Returns NULL if none are available.
 377 static ObjectMonitor* take_from_start_of_common(ObjectMonitor** list_p,
 378                                                 int* count_p) {
 379   ObjectMonitor* take = NULL;
 380   // Lock the list head to guard against races with a list walker
 381   // or async deflater thread (which only races in om_list_globals._free_list):
 382   if ((take = get_list_head_locked(list_p)) == NULL) {
 383     return NULL;  // None are available.
 384   }
 385   ObjectMonitor* next = unmarked_next(take);
 386   // Switch locked list head to next (which unlocks the list head, but
 387   // leaves take locked):
 388   Atomic::store(list_p, next);
 389   Atomic::dec(count_p);
 390   // Unlock take, but leave the next value for any lagging list
 391   // walkers. It will get cleaned up when take is prepended to
 392   // the in-use list:
 393   om_unlock(take);
 394   return take;
 395 }
 396 
 397 // Take an ObjectMonitor from the start of the om_list_globals._free_list.
 398 // Also updates om_list_globals._free_count. Returns NULL if none are
 399 // available.
 400 static ObjectMonitor* take_from_start_of_global_free_list() {
 401   return take_from_start_of_common(&om_list_globals._free_list,
 402                                    &om_list_globals._free_count);
 403 }
 404 
 405 // Take an ObjectMonitor from the start of a per-thread free-list.
 406 // Also updates om_free_count. Returns NULL if none are available.
 407 static ObjectMonitor* take_from_start_of_om_free_list(Thread* self) {
 408   return take_from_start_of_common(&self->om_free_list, &self->om_free_count);
 409 }
 410 
 411 
 412 // =====================> Quick functions
 413 
 414 // The quick_* forms are special fast-path variants used to improve
 415 // performance.  In the simplest case, a "quick_*" implementation could
 416 // simply return false, in which case the caller will perform the necessary
 417 // state transitions and call the slow-path form.
 418 // The fast-path is designed to handle frequently arising cases in an efficient
 419 // manner and is just a degenerate "optimistic" variant of the slow-path.
 420 // returns true  -- to indicate the call was satisfied.
 421 // returns false -- to indicate the call needs the services of the slow-path.
 422 // A no-loitering ordinance is in effect for code in the quick_* family
 423 // operators: safepoints or indefinite blocking (blocking that might span a
 424 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon
 425 // entry.
 426 //
 427 // Consider: An interesting optimization is to have the JIT recognize the
 428 // following common idiom:
 429 //   synchronized (someobj) { .... ; notify(); }
 430 // That is, we find a notify() or notifyAll() call that immediately precedes
 431 // the monitorexit operation.  In that case the JIT could fuse the operations
 432 // into a single notifyAndExit() runtime primitive.
 433 
 434 bool ObjectSynchronizer::quick_notify(oopDesc* obj, Thread* self, bool all) {
 435   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 436   assert(self->is_Java_thread(), "invariant");
 437   assert(((JavaThread *) self)->thread_state() == _thread_in_Java, "invariant");
 438   NoSafepointVerifier nsv;
 439   if (obj == NULL) return false;  // slow-path for invalid obj
 440   const markWord mark = obj->mark();
 441 
 442   if (mark.has_locker() && self->is_lock_owned((address)mark.locker())) {
 443     // Degenerate notify
 444     // stack-locked by caller so by definition the implied waitset is empty.
 445     return true;
 446   }
 447 
 448   if (mark.has_monitor()) {
 449     ObjectMonitor* const mon = mark.monitor();
 450     assert(mon->object() == obj, "invariant");
 451     if (mon->owner() != self) return false;  // slow-path for IMS exception
 452 
 453     if (mon->first_waiter() != NULL) {
 454       // We have one or more waiters. Since this is an inflated monitor
 455       // that we own, we can transfer one or more threads from the waitset
 456       // to the entrylist here and now, avoiding the slow-path.
 457       if (all) {
 458         DTRACE_MONITOR_PROBE(notifyAll, mon, obj, self);
 459       } else {
 460         DTRACE_MONITOR_PROBE(notify, mon, obj, self);
 461       }
 462       int free_count = 0;
 463       do {
 464         mon->INotify(self);
 465         ++free_count;
 466       } while (mon->first_waiter() != NULL && all);
 467       OM_PERFDATA_OP(Notifications, inc(free_count));
 468     }
 469     return true;
 470   }
 471 
 472   // biased locking and any other IMS exception states take the slow-path
 473   return false;
 474 }
 475 
 476 
 477 // The LockNode emitted directly at the synchronization site would have
 478 // been too big if it were to have included support for the cases of inflated
 479 // recursive enter and exit, so they go here instead.
 480 // Note that we can't safely call AsyncPrintJavaStack() from within
 481 // quick_enter() as our thread state remains _in_Java.
 482 
 483 bool ObjectSynchronizer::quick_enter(oop obj, Thread* self,
 484                                      BasicLock * lock) {
 485   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 486   assert(self->is_Java_thread(), "invariant");
 487   assert(((JavaThread *) self)->thread_state() == _thread_in_Java, "invariant");
 488   NoSafepointVerifier nsv;
 489   if (obj == NULL) return false;       // Need to throw NPE
 490 
 491   const markWord mark = obj->mark();
 492 
 493   if (mark.has_monitor()) {
 494     ObjectMonitor* const m = mark.monitor();
 495     if (AsyncDeflateIdleMonitors) {
 496       // An async deflation can race us before we manage to make the
 497       // ObjectMonitor busy by setting the owner below. If we detect
 498       // that race we just bail out to the slow-path here.
 499       if (m->object() == NULL) {
 500         return false;
 501       }
 502     } else {
 503       assert(m->object() == obj, "invariant");
 504     }
 505     Thread* const owner = (Thread *) m->_owner;
 506 
 507     // Lock contention and Transactional Lock Elision (TLE) diagnostics
 508     // and observability
 509     // Case: light contention possibly amenable to TLE
 510     // Case: TLE inimical operations such as nested/recursive synchronization
 511 
 512     if (owner == self) {
 513       m->_recursions++;
 514       return true;
 515     }
 516 
 517     // This Java Monitor is inflated so obj's header will never be
 518     // displaced to this thread's BasicLock. Make the displaced header
 519     // non-NULL so this BasicLock is not seen as recursive nor as
 520     // being locked. We do this unconditionally so that this thread's
 521     // BasicLock cannot be mis-interpreted by any stack walkers. For
 522     // performance reasons, stack walkers generally first check for
 523     // Biased Locking in the object's header, the second check is for
 524     // stack-locking in the object's header, the third check is for
 525     // recursive stack-locking in the displaced header in the BasicLock,
 526     // and last are the inflated Java Monitor (ObjectMonitor) checks.
 527     lock->set_displaced_header(markWord::unused_mark());
 528 
 529     if (owner == NULL && m->try_set_owner_from(NULL, self) == NULL) {
 530       assert(m->_recursions == 0, "invariant");
 531       return true;
 532     }
 533   }
 534 
 535   // Note that we could inflate in quick_enter.
 536   // This is likely a useful optimization
 537   // Critically, in quick_enter() we must not:
 538   // -- perform bias revocation, or
 539   // -- block indefinitely, or
 540   // -- reach a safepoint
 541 
 542   return false;        // revert to slow-path
 543 }
 544 
 545 // -----------------------------------------------------------------------------
 546 // Monitor Enter/Exit
 547 // The interpreter and compiler assembly code tries to lock using the fast path
 548 // of this algorithm. Make sure to update that code if the following function is
 549 // changed. The implementation is extremely sensitive to race condition. Be careful.
 550 
 551 void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, TRAPS) {
 552   if (UseBiasedLocking) {
 553     if (!SafepointSynchronize::is_at_safepoint()) {
 554       BiasedLocking::revoke(obj, THREAD);
 555     } else {
 556       BiasedLocking::revoke_at_safepoint(obj);
 557     }
 558   }
 559 
 560   markWord mark = obj->mark();
 561   assert(!mark.has_bias_pattern(), "should not see bias pattern here");
 562 
 563   if (mark.is_neutral()) {
 564     // Anticipate successful CAS -- the ST of the displaced mark must
 565     // be visible <= the ST performed by the CAS.
 566     lock->set_displaced_header(mark);
 567     if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) {
 568       return;
 569     }
 570     // Fall through to inflate() ...
 571   } else if (mark.has_locker() &&
 572              THREAD->is_lock_owned((address)mark.locker())) {
 573     assert(lock != mark.locker(), "must not re-lock the same lock");
 574     assert(lock != (BasicLock*)obj->mark().value(), "don't relock with same BasicLock");
 575     lock->set_displaced_header(markWord::from_pointer(NULL));
 576     return;
 577   }
 578 
 579   // The object header will never be displaced to this lock,
 580   // so it does not matter what the value is, except that it
 581   // must be non-zero to avoid looking like a re-entrant lock,
 582   // and must not look locked either.
 583   lock->set_displaced_header(markWord::unused_mark());
 584   // An async deflation can race after the inflate() call and before
 585   // enter() can make the ObjectMonitor busy. enter() returns false if
 586   // we have lost the race to async deflation and we simply try again.
 587   while (true) {
 588     ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_monitor_enter);
 589     if (monitor->enter(THREAD)) {
 590       return;
 591     }
 592   }
 593 }
 594 
 595 void ObjectSynchronizer::exit(oop object, BasicLock* lock, TRAPS) {
 596   markWord mark = object->mark();
 597   // We cannot check for Biased Locking if we are racing an inflation.
 598   assert(mark == markWord::INFLATING() ||
 599          !mark.has_bias_pattern(), "should not see bias pattern here");
 600 
 601   markWord dhw = lock->displaced_header();
 602   if (dhw.value() == 0) {
 603     // If the displaced header is NULL, then this exit matches up with
 604     // a recursive enter. No real work to do here except for diagnostics.
 605 #ifndef PRODUCT
 606     if (mark != markWord::INFLATING()) {
 607       // Only do diagnostics if we are not racing an inflation. Simply
 608       // exiting a recursive enter of a Java Monitor that is being
 609       // inflated is safe; see the has_monitor() comment below.
 610       assert(!mark.is_neutral(), "invariant");
 611       assert(!mark.has_locker() ||
 612              THREAD->is_lock_owned((address)mark.locker()), "invariant");
 613       if (mark.has_monitor()) {
 614         // The BasicLock's displaced_header is marked as a recursive
 615         // enter and we have an inflated Java Monitor (ObjectMonitor).
 616         // This is a special case where the Java Monitor was inflated
 617         // after this thread entered the stack-lock recursively. When a
 618         // Java Monitor is inflated, we cannot safely walk the Java
 619         // Monitor owner's stack and update the BasicLocks because a
 620         // Java Monitor can be asynchronously inflated by a thread that
 621         // does not own the Java Monitor.
 622         ObjectMonitor* m = mark.monitor();
 623         assert(((oop)(m->object()))->mark() == mark, "invariant");
 624         assert(m->is_entered(THREAD), "invariant");
 625       }
 626     }
 627 #endif
 628     return;
 629   }
 630 
 631   if (mark == markWord::from_pointer(lock)) {
 632     // If the object is stack-locked by the current thread, try to
 633     // swing the displaced header from the BasicLock back to the mark.
 634     assert(dhw.is_neutral(), "invariant");
 635     if (object->cas_set_mark(dhw, mark) == mark) {
 636       return;
 637     }
 638   }
 639 
 640   // We have to take the slow-path of possible inflation and then exit.
 641   // The ObjectMonitor* can't be async deflated until ownership is
 642   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 643   ObjectMonitor* monitor = inflate(THREAD, object, inflate_cause_vm_internal);
 644   monitor->exit(true, THREAD);
 645 }
 646 
 647 // -----------------------------------------------------------------------------
 648 // Class Loader  support to workaround deadlocks on the class loader lock objects
 649 // Also used by GC
 650 // complete_exit()/reenter() are used to wait on a nested lock
 651 // i.e. to give up an outer lock completely and then re-enter
 652 // Used when holding nested locks - lock acquisition order: lock1 then lock2
 653 //  1) complete_exit lock1 - saving recursion count
 654 //  2) wait on lock2
 655 //  3) when notified on lock2, unlock lock2
 656 //  4) reenter lock1 with original recursion count
 657 //  5) lock lock2
 658 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 659 intx ObjectSynchronizer::complete_exit(Handle obj, TRAPS) {
 660   if (UseBiasedLocking) {
 661     BiasedLocking::revoke(obj, THREAD);
 662     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 663   }
 664 
 665   // The ObjectMonitor* can't be async deflated until ownership is
 666   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 667   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_vm_internal);
 668   intptr_t ret_code = monitor->complete_exit(THREAD);
 669   return ret_code;
 670 }
 671 
 672 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 673 void ObjectSynchronizer::reenter(Handle obj, intx recursions, TRAPS) {
 674   if (UseBiasedLocking) {
 675     BiasedLocking::revoke(obj, THREAD);
 676     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 677   }
 678 
 679   // An async deflation can race after the inflate() call and before
 680   // reenter() -> enter() can make the ObjectMonitor busy. reenter() ->
 681   // enter() returns false if we have lost the race to async deflation
 682   // and we simply try again.
 683   while (true) {
 684     ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_vm_internal);
 685     if (monitor->reenter(recursions, THREAD)) {
 686       return;
 687     }
 688   }
 689 }
 690 
 691 // -----------------------------------------------------------------------------
 692 // JNI locks on java objects
 693 // NOTE: must use heavy weight monitor to handle jni monitor enter
 694 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) {
 695   // the current locking is from JNI instead of Java code
 696   if (UseBiasedLocking) {
 697     BiasedLocking::revoke(obj, THREAD);
 698     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 699   }
 700   THREAD->set_current_pending_monitor_is_from_java(false);
 701   // An async deflation can race after the inflate() call and before
 702   // enter() can make the ObjectMonitor busy. enter() returns false if
 703   // we have lost the race to async deflation and we simply try again.
 704   while (true) {
 705     ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_jni_enter);
 706     if (monitor->enter(THREAD)) {
 707       break;
 708     }
 709   }
 710   THREAD->set_current_pending_monitor_is_from_java(true);
 711 }
 712 
 713 // NOTE: must use heavy weight monitor to handle jni monitor exit
 714 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
 715   if (UseBiasedLocking) {
 716     Handle h_obj(THREAD, obj);
 717     BiasedLocking::revoke(h_obj, THREAD);
 718     obj = h_obj();
 719   }
 720   assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 721 
 722   // The ObjectMonitor* can't be async deflated until ownership is
 723   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 724   ObjectMonitor* monitor = inflate(THREAD, obj, inflate_cause_jni_exit);
 725   // If this thread has locked the object, exit the monitor. We
 726   // intentionally do not use CHECK here because we must exit the
 727   // monitor even if an exception is pending.
 728   if (monitor->check_owner(THREAD)) {
 729     monitor->exit(true, THREAD);
 730   }
 731 }
 732 
 733 // -----------------------------------------------------------------------------
 734 // Internal VM locks on java objects
 735 // standard constructor, allows locking failures
 736 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool do_lock) {
 737   _dolock = do_lock;
 738   _thread = thread;
 739   _thread->check_for_valid_safepoint_state();
 740   _obj = obj;
 741 
 742   if (_dolock) {
 743     ObjectSynchronizer::enter(_obj, &_lock, _thread);
 744   }
 745 }
 746 
 747 ObjectLocker::~ObjectLocker() {
 748   if (_dolock) {
 749     ObjectSynchronizer::exit(_obj(), &_lock, _thread);
 750   }
 751 }
 752 
 753 
 754 // -----------------------------------------------------------------------------
 755 //  Wait/Notify/NotifyAll
 756 // NOTE: must use heavy weight monitor to handle wait()
 757 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 758   if (UseBiasedLocking) {
 759     BiasedLocking::revoke(obj, THREAD);
 760     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 761   }
 762   if (millis < 0) {
 763     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 764   }
 765   // The ObjectMonitor* can't be async deflated because the _waiters
 766   // field is incremented before ownership is dropped and decremented
 767   // after ownership is regained.
 768   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_wait);
 769 
 770   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);
 771   monitor->wait(millis, true, THREAD);
 772 
 773   // This dummy call is in place to get around dtrace bug 6254741.  Once
 774   // that's fixed we can uncomment the following line, remove the call
 775   // and change this function back into a "void" func.
 776   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 777   int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
 778   return ret_code;
 779 }
 780 
 781 void ObjectSynchronizer::wait_uninterruptibly(Handle obj, jlong millis, TRAPS) {
 782   if (UseBiasedLocking) {
 783     BiasedLocking::revoke(obj, THREAD);
 784     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 785   }
 786   if (millis < 0) {
 787     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 788   }
 789   // The ObjectMonitor* can't be async deflated because the _waiters
 790   // field is incremented before ownership is dropped and decremented
 791   // after ownership is regained.
 792   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_wait);
 793   monitor->wait(millis, false, THREAD);
 794 }
 795 
 796 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 797   if (UseBiasedLocking) {
 798     BiasedLocking::revoke(obj, THREAD);
 799     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 800   }
 801 
 802   markWord mark = obj->mark();
 803   if (mark.has_locker() && THREAD->is_lock_owned((address)mark.locker())) {
 804     return;
 805   }
 806   // The ObjectMonitor* can't be async deflated until ownership is
 807   // dropped by the calling thread.
 808   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_notify);
 809   monitor->notify(THREAD);
 810 }
 811 
 812 // NOTE: see comment of notify()
 813 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 814   if (UseBiasedLocking) {
 815     BiasedLocking::revoke(obj, THREAD);
 816     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 817   }
 818 
 819   markWord mark = obj->mark();
 820   if (mark.has_locker() && THREAD->is_lock_owned((address)mark.locker())) {
 821     return;
 822   }
 823   // The ObjectMonitor* can't be async deflated until ownership is
 824   // dropped by the calling thread.
 825   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_notify);
 826   monitor->notifyAll(THREAD);
 827 }
 828 
 829 // -----------------------------------------------------------------------------
 830 // Hash Code handling
 831 //
 832 // Performance concern:
 833 // OrderAccess::storestore() calls release() which at one time stored 0
 834 // into the global volatile OrderAccess::dummy variable. This store was
 835 // unnecessary for correctness. Many threads storing into a common location
 836 // causes considerable cache migration or "sloshing" on large SMP systems.
 837 // As such, I avoided using OrderAccess::storestore(). In some cases
 838 // OrderAccess::fence() -- which incurs local latency on the executing
 839 // processor -- is a better choice as it scales on SMP systems.
 840 //
 841 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for
 842 // a discussion of coherency costs. Note that all our current reference
 843 // platforms provide strong ST-ST order, so the issue is moot on IA32,
 844 // x64, and SPARC.
 845 //
 846 // As a general policy we use "volatile" to control compiler-based reordering
 847 // and explicit fences (barriers) to control for architectural reordering
 848 // performed by the CPU(s) or platform.
 849 
 850 struct SharedGlobals {
 851   char         _pad_prefix[OM_CACHE_LINE_SIZE];
 852   // These are highly shared mostly-read variables.
 853   // To avoid false-sharing they need to be the sole occupants of a cache line.
 854   volatile int stw_random;
 855   volatile int stw_cycle;
 856   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int) * 2);
 857   // Hot RW variable -- Sequester to avoid false-sharing
 858   volatile int hc_sequence;
 859   DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 860 };
 861 
 862 static SharedGlobals GVars;
 863 
 864 static markWord read_stable_mark(oop obj) {
 865   markWord mark = obj->mark();
 866   if (!mark.is_being_inflated()) {
 867     return mark;       // normal fast-path return
 868   }
 869 
 870   int its = 0;
 871   for (;;) {
 872     markWord mark = obj->mark();
 873     if (!mark.is_being_inflated()) {
 874       return mark;    // normal fast-path return
 875     }
 876 
 877     // The object is being inflated by some other thread.
 878     // The caller of read_stable_mark() must wait for inflation to complete.
 879     // Avoid live-lock
 880     // TODO: consider calling SafepointSynchronize::do_call_back() while
 881     // spinning to see if there's a safepoint pending.  If so, immediately
 882     // yielding or blocking would be appropriate.  Avoid spinning while
 883     // there is a safepoint pending.
 884     // TODO: add inflation contention performance counters.
 885     // TODO: restrict the aggregate number of spinners.
 886 
 887     ++its;
 888     if (its > 10000 || !os::is_MP()) {
 889       if (its & 1) {
 890         os::naked_yield();
 891       } else {
 892         // Note that the following code attenuates the livelock problem but is not
 893         // a complete remedy.  A more complete solution would require that the inflating
 894         // thread hold the associated inflation lock.  The following code simply restricts
 895         // the number of spinners to at most one.  We'll have N-2 threads blocked
 896         // on the inflationlock, 1 thread holding the inflation lock and using
 897         // a yield/park strategy, and 1 thread in the midst of inflation.
 898         // A more refined approach would be to change the encoding of INFLATING
 899         // to allow encapsulation of a native thread pointer.  Threads waiting for
 900         // inflation to complete would use CAS to push themselves onto a singly linked
 901         // list rooted at the markword.  Once enqueued, they'd loop, checking a per-thread flag
 902         // and calling park().  When inflation was complete the thread that accomplished inflation
 903         // would detach the list and set the markword to inflated with a single CAS and
 904         // then for each thread on the list, set the flag and unpark() the thread.
 905         // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease
 906         // wakes at most one thread whereas we need to wake the entire list.
 907         int ix = (cast_from_oop<intptr_t>(obj) >> 5) & (NINFLATIONLOCKS-1);
 908         int YieldThenBlock = 0;
 909         assert(ix >= 0 && ix < NINFLATIONLOCKS, "invariant");
 910         assert((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant");
 911         Thread::muxAcquire(gInflationLocks + ix, "gInflationLock");
 912         while (obj->mark() == markWord::INFLATING()) {
 913           // Beware: NakedYield() is advisory and has almost no effect on some platforms
 914           // so we periodically call self->_ParkEvent->park(1).
 915           // We use a mixed spin/yield/block mechanism.
 916           if ((YieldThenBlock++) >= 16) {
 917             Thread::current()->_ParkEvent->park(1);
 918           } else {
 919             os::naked_yield();
 920           }
 921         }
 922         Thread::muxRelease(gInflationLocks + ix);
 923       }
 924     } else {
 925       SpinPause();       // SMP-polite spinning
 926     }
 927   }
 928 }
 929 
 930 // hashCode() generation :
 931 //
 932 // Possibilities:
 933 // * MD5Digest of {obj,stw_random}
 934 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function.
 935 // * A DES- or AES-style SBox[] mechanism
 936 // * One of the Phi-based schemes, such as:
 937 //   2654435761 = 2^32 * Phi (golden ratio)
 938 //   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ;
 939 // * A variation of Marsaglia's shift-xor RNG scheme.
 940 // * (obj ^ stw_random) is appealing, but can result
 941 //   in undesirable regularity in the hashCode values of adjacent objects
 942 //   (objects allocated back-to-back, in particular).  This could potentially
 943 //   result in hashtable collisions and reduced hashtable efficiency.
 944 //   There are simple ways to "diffuse" the middle address bits over the
 945 //   generated hashCode values:
 946 
 947 static inline intptr_t get_next_hash(Thread* self, oop obj) {
 948   intptr_t value = 0;
 949   if (hashCode == 0) {
 950     // This form uses global Park-Miller RNG.
 951     // On MP system we'll have lots of RW access to a global, so the
 952     // mechanism induces lots of coherency traffic.
 953     value = os::random();
 954   } else if (hashCode == 1) {
 955     // This variation has the property of being stable (idempotent)
 956     // between STW operations.  This can be useful in some of the 1-0
 957     // synchronization schemes.
 958     intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3;
 959     value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random;
 960   } else if (hashCode == 2) {
 961     value = 1;            // for sensitivity testing
 962   } else if (hashCode == 3) {
 963     value = ++GVars.hc_sequence;
 964   } else if (hashCode == 4) {
 965     value = cast_from_oop<intptr_t>(obj);
 966   } else {
 967     // Marsaglia's xor-shift scheme with thread-specific state
 968     // This is probably the best overall implementation -- we'll
 969     // likely make this the default in future releases.
 970     unsigned t = self->_hashStateX;
 971     t ^= (t << 11);
 972     self->_hashStateX = self->_hashStateY;
 973     self->_hashStateY = self->_hashStateZ;
 974     self->_hashStateZ = self->_hashStateW;
 975     unsigned v = self->_hashStateW;
 976     v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
 977     self->_hashStateW = v;
 978     value = v;
 979   }
 980 
 981   value &= markWord::hash_mask;
 982   if (value == 0) value = 0xBAD;
 983   assert(value != markWord::no_hash, "invariant");
 984   return value;
 985 }
 986 
 987 intptr_t ObjectSynchronizer::FastHashCode(Thread* self, oop obj) {
 988   if (UseBiasedLocking) {
 989     // NOTE: many places throughout the JVM do not expect a safepoint
 990     // to be taken here, in particular most operations on perm gen
 991     // objects. However, we only ever bias Java instances and all of
 992     // the call sites of identity_hash that might revoke biases have
 993     // been checked to make sure they can handle a safepoint. The
 994     // added check of the bias pattern is to avoid useless calls to
 995     // thread-local storage.
 996     if (obj->mark().has_bias_pattern()) {
 997       // Handle for oop obj in case of STW safepoint
 998       Handle hobj(self, obj);
 999       // Relaxing assertion for bug 6320749.
1000       assert(Universe::verify_in_progress() ||
1001              !SafepointSynchronize::is_at_safepoint(),
1002              "biases should not be seen by VM thread here");
1003       BiasedLocking::revoke(hobj, JavaThread::current());
1004       obj = hobj();
1005       assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
1006     }
1007   }
1008 
1009   // hashCode() is a heap mutator ...
1010   // Relaxing assertion for bug 6320749.
1011   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
1012          !SafepointSynchronize::is_at_safepoint(), "invariant");
1013   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
1014          self->is_Java_thread() , "invariant");
1015   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
1016          ((JavaThread *)self)->thread_state() != _thread_blocked, "invariant");
1017 
1018   while (true) {
1019     ObjectMonitor* monitor = NULL;
1020     markWord temp, test;
1021     intptr_t hash;
1022     markWord mark = read_stable_mark(obj);
1023 
1024     // object should remain ineligible for biased locking
1025     assert(!mark.has_bias_pattern(), "invariant");
1026 
1027     if (mark.is_neutral()) {            // if this is a normal header
1028       hash = mark.hash();
1029       if (hash != 0) {                  // if it has a hash, just return it
1030         return hash;
1031       }
1032       hash = get_next_hash(self, obj);  // get a new hash
1033       temp = mark.copy_set_hash(hash);  // merge the hash into header
1034                                         // try to install the hash
1035       test = obj->cas_set_mark(temp, mark);
1036       if (test == mark) {               // if the hash was installed, return it
1037         return hash;
1038       }
1039       // Failed to install the hash. It could be that another thread
1040       // installed the hash just before our attempt or inflation has
1041       // occurred or... so we fall thru to inflate the monitor for
1042       // stability and then install the hash.
1043     } else if (mark.has_monitor()) {
1044       // The first stage of a racing async deflation won't affect the
1045       // hash value if this ObjectMonitor happens to already have one.
1046       monitor = mark.monitor();
1047       temp = monitor->header();
1048       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
1049       hash = temp.hash();
1050       if (hash != 0) {                  // if it has a hash, just return it
1051         return hash;
1052       }
1053       // Fall thru so we only have one place that installs the hash in
1054       // the ObjectMonitor.
1055     } else if (self->is_lock_owned((address)mark.locker())) {
1056       // This is a stack lock owned by the calling thread so fetch the
1057       // displaced markWord from the BasicLock on the stack.
1058       temp = mark.displaced_mark_helper();
1059       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
1060       hash = temp.hash();
1061       if (hash != 0) {                  // if it has a hash, just return it
1062         return hash;
1063       }
1064       // WARNING:
1065       // The displaced header in the BasicLock on a thread's stack
1066       // is strictly immutable. It CANNOT be changed in ANY cases.
1067       // So we have to inflate the stack lock into an ObjectMonitor
1068       // even if the current thread owns the lock. The BasicLock on
1069       // a thread's stack can be asynchronously read by other threads
1070       // during an inflate() call so any change to that stack memory
1071       // may not propagate to other threads correctly.
1072     }
1073 
1074     // Inflate the monitor to set the hash.
1075 
1076     // An async deflation can race after the inflate() call and before we
1077     // can update the ObjectMonitor's header with the hash value below.
1078     monitor = inflate(self, obj, inflate_cause_hash_code);
1079     // Load ObjectMonitor's header/dmw field and see if it has a hash.
1080     mark = monitor->header();
1081     assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
1082     hash = mark.hash();
1083     if (hash == 0) {                    // if it does not have a hash
1084       hash = get_next_hash(self, obj);  // get a new hash
1085       temp = mark.copy_set_hash(hash);  // merge the hash into header
1086       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
1087       uintptr_t v = Atomic::cmpxchg((volatile uintptr_t*)monitor->header_addr(), mark.value(), temp.value());
1088       test = markWord(v);
1089       if (test != mark) {
1090         // The attempt to update the ObjectMonitor's header/dmw field
1091         // did not work. This can happen if another thread managed to
1092         // merge in the hash just before our cmpxchg().
1093         // If we add any new usages of the header/dmw field, this code
1094         // will need to be updated.
1095         hash = test.hash();
1096         assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value());
1097         assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash");
1098       }
1099       if (monitor->is_being_async_deflated()) {
1100         // If we detect that async deflation has occurred, then we
1101         // simply retry so that the hash value can be stored in either
1102         // the object's header or in the re-inflated ObjectMonitor's
1103         // header as appropriate.
1104         continue;
1105       }
1106     }
1107     // We finally get the hash.
1108     return hash;
1109   }
1110 }
1111 
1112 // Deprecated -- use FastHashCode() instead.
1113 
1114 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
1115   return FastHashCode(Thread::current(), obj());
1116 }
1117 
1118 
1119 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread,
1120                                                    Handle h_obj) {
1121   if (UseBiasedLocking) {
1122     BiasedLocking::revoke(h_obj, thread);
1123     assert(!h_obj->mark().has_bias_pattern(), "biases should be revoked by now");
1124   }
1125 
1126   assert(thread == JavaThread::current(), "Can only be called on current thread");
1127   oop obj = h_obj();
1128 
1129   markWord mark = read_stable_mark(obj);
1130 
1131   // Uncontended case, header points to stack
1132   if (mark.has_locker()) {
1133     return thread->is_lock_owned((address)mark.locker());
1134   }
1135   // Contended case, header points to ObjectMonitor (tagged pointer)
1136   if (mark.has_monitor()) {
1137     // The first stage of async deflation does not affect any field
1138     // used by this comparison so the ObjectMonitor* is usable here.
1139     ObjectMonitor* monitor = mark.monitor();
1140     return monitor->is_entered(thread) != 0;
1141   }
1142   // Unlocked case, header in place
1143   assert(mark.is_neutral(), "sanity check");
1144   return false;
1145 }
1146 
1147 // Be aware of this method could revoke bias of the lock object.
1148 // This method queries the ownership of the lock handle specified by 'h_obj'.
1149 // If the current thread owns the lock, it returns owner_self. If no
1150 // thread owns the lock, it returns owner_none. Otherwise, it will return
1151 // owner_other.
1152 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership
1153 (JavaThread *self, Handle h_obj) {
1154   // The caller must beware this method can revoke bias, and
1155   // revocation can result in a safepoint.
1156   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
1157   assert(self->thread_state() != _thread_blocked, "invariant");
1158 
1159   // Possible mark states: neutral, biased, stack-locked, inflated
1160 
1161   if (UseBiasedLocking && h_obj()->mark().has_bias_pattern()) {
1162     // CASE: biased
1163     BiasedLocking::revoke(h_obj, self);
1164     assert(!h_obj->mark().has_bias_pattern(),
1165            "biases should be revoked by now");
1166   }
1167 
1168   assert(self == JavaThread::current(), "Can only be called on current thread");
1169   oop obj = h_obj();
1170   markWord mark = read_stable_mark(obj);
1171 
1172   // CASE: stack-locked.  Mark points to a BasicLock on the owner's stack.
1173   if (mark.has_locker()) {
1174     return self->is_lock_owned((address)mark.locker()) ?
1175       owner_self : owner_other;
1176   }
1177 
1178   // CASE: inflated. Mark (tagged pointer) points to an ObjectMonitor.
1179   // The Object:ObjectMonitor relationship is stable as long as we're
1180   // not at a safepoint and AsyncDeflateIdleMonitors is false.
1181   if (mark.has_monitor()) {
1182     // The first stage of async deflation does not affect any field
1183     // used by this comparison so the ObjectMonitor* is usable here.
1184     ObjectMonitor* monitor = mark.monitor();
1185     void* owner = monitor->owner();
1186     if (owner == NULL) return owner_none;
1187     return (owner == self ||
1188             self->is_lock_owned((address)owner)) ? owner_self : owner_other;
1189   }
1190 
1191   // CASE: neutral
1192   assert(mark.is_neutral(), "sanity check");
1193   return owner_none;           // it's unlocked
1194 }
1195 
1196 // FIXME: jvmti should call this
1197 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
1198   if (UseBiasedLocking) {
1199     if (SafepointSynchronize::is_at_safepoint()) {
1200       BiasedLocking::revoke_at_safepoint(h_obj);
1201     } else {
1202       BiasedLocking::revoke(h_obj, JavaThread::current());
1203     }
1204     assert(!h_obj->mark().has_bias_pattern(), "biases should be revoked by now");
1205   }
1206 
1207   oop obj = h_obj();
1208   address owner = NULL;
1209 
1210   markWord mark = read_stable_mark(obj);
1211 
1212   // Uncontended case, header points to stack
1213   if (mark.has_locker()) {
1214     owner = (address) mark.locker();
1215   }
1216 
1217   // Contended case, header points to ObjectMonitor (tagged pointer)
1218   else if (mark.has_monitor()) {
1219     // The first stage of async deflation does not affect any field
1220     // used by this comparison so the ObjectMonitor* is usable here.
1221     ObjectMonitor* monitor = mark.monitor();
1222     assert(monitor != NULL, "monitor should be non-null");
1223     owner = (address) monitor->owner();
1224   }
1225 
1226   if (owner != NULL) {
1227     // owning_thread_from_monitor_owner() may also return NULL here
1228     return Threads::owning_thread_from_monitor_owner(t_list, owner);
1229   }
1230 
1231   // Unlocked case, header in place
1232   // Cannot have assertion since this object may have been
1233   // locked by another thread when reaching here.
1234   // assert(mark.is_neutral(), "sanity check");
1235 
1236   return NULL;
1237 }
1238 
1239 // Visitors ...
1240 
1241 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) {
1242   PaddedObjectMonitor* block = Atomic::load(&g_block_list);
1243   while (block != NULL) {
1244     assert(block->object() == CHAINMARKER, "must be a block header");
1245     for (int i = _BLOCKSIZE - 1; i > 0; i--) {
1246       ObjectMonitor* mid = (ObjectMonitor *)(block + i);
1247       if (!mid->is_free() && mid->object() != NULL) {
1248         // Only process with closure if the object is set.
1249 
1250         // monitors_iterate() is only called at a safepoint or when the
1251         // target thread is suspended or when the target thread is
1252         // operating on itself. The closures are only interested in an
1253         // owned ObjectMonitor and ownership cannot be dropped under the
1254         // calling contexts so the ObjectMonitor cannot be async deflated.
1255         closure->do_monitor(mid);
1256       }
1257     }
1258     // unmarked_next() is not needed with g_block_list (no locking
1259     // used with block linkage _next_om fields).
1260     block = (PaddedObjectMonitor*)block->next_om();
1261   }
1262 }
1263 
1264 static bool monitors_used_above_threshold() {
1265   int population = Atomic::load(&om_list_globals._population);
1266   if (population == 0) {
1267     return false;
1268   }
1269   if (MonitorUsedDeflationThreshold > 0) {
1270     int monitors_used = population - Atomic::load(&om_list_globals._free_count) -
1271                         Atomic::load(&om_list_globals._wait_count);
1272     int monitor_usage = (monitors_used * 100LL) / population;
1273     return monitor_usage > MonitorUsedDeflationThreshold;
1274   }
1275   return false;
1276 }
1277 
1278 bool ObjectSynchronizer::is_async_deflation_needed() {
1279   if (!AsyncDeflateIdleMonitors) {
1280     return false;
1281   }
1282   if (is_async_deflation_requested()) {
1283     // Async deflation request.
1284     return true;
1285   }
1286   if (AsyncDeflationInterval > 0 &&
1287       time_since_last_async_deflation_ms() > AsyncDeflationInterval &&
1288       monitors_used_above_threshold()) {
1289     // It's been longer than our specified deflate interval and there
1290     // are too many monitors in use. We don't deflate more frequently
1291     // than AsyncDeflationInterval (unless is_async_deflation_requested)
1292     // in order to not swamp the ServiceThread.
1293     _last_async_deflation_time_ns = os::javaTimeNanos();
1294     return true;
1295   }
1296   return false;
1297 }
1298 
1299 bool ObjectSynchronizer::is_safepoint_deflation_needed() {
1300   if (!AsyncDeflateIdleMonitors) {
1301     if (monitors_used_above_threshold()) {
1302       // Too many monitors in use.
1303       return true;
1304     }
1305     return false;
1306   }
1307   if (is_special_deflation_requested()) {
1308     // For AsyncDeflateIdleMonitors only do a safepoint deflation
1309     // if there is a special deflation request.
1310     return true;
1311   }
1312   return false;
1313 }
1314 
1315 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() {
1316   return (os::javaTimeNanos() - _last_async_deflation_time_ns) / (NANOUNITS / MILLIUNITS);
1317 }
1318 
1319 void ObjectSynchronizer::oops_do(OopClosure* f) {
1320   // We only scan the global used list here (for moribund threads), and
1321   // the thread-local monitors in Thread::oops_do().
1322   global_used_oops_do(f);
1323 }
1324 
1325 void ObjectSynchronizer::global_used_oops_do(OopClosure* f) {
1326   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1327   list_oops_do(Atomic::load(&om_list_globals._in_use_list), f);
1328 }
1329 
1330 void ObjectSynchronizer::thread_local_used_oops_do(Thread* thread, OopClosure* f) {
1331   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1332   list_oops_do(thread->om_in_use_list, f);
1333 }
1334 
1335 void ObjectSynchronizer::list_oops_do(ObjectMonitor* list, OopClosure* f) {
1336   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1337   // The oops_do() phase does not overlap with monitor deflation
1338   // so no need to lock ObjectMonitors for the list traversal.
1339   for (ObjectMonitor* mid = list; mid != NULL; mid = unmarked_next(mid)) {
1340     if (mid->object() != NULL) {
1341       f->do_oop((oop*)mid->object_addr());
1342     }
1343   }
1344 }
1345 
1346 
1347 // -----------------------------------------------------------------------------
1348 // ObjectMonitor Lifecycle
1349 // -----------------------
1350 // Inflation unlinks monitors from om_list_globals._free_list or a per-thread
1351 // free list and associates them with objects. Deflation -- which occurs at
1352 // STW-time or asynchronously -- disassociates idle monitors from objects.
1353 // Such scavenged monitors are returned to the om_list_globals._free_list.
1354 //
1355 // ObjectMonitors reside in type-stable memory (TSM) and are immortal.
1356 //
1357 // Lifecycle:
1358 // --   unassigned and on the om_list_globals._free_list
1359 // --   unassigned and on a per-thread free list
1360 // --   assigned to an object.  The object is inflated and the mark refers
1361 //      to the ObjectMonitor.
1362 
1363 ObjectMonitor* ObjectSynchronizer::om_alloc(Thread* self) {
1364   // A large MAXPRIVATE value reduces both list lock contention
1365   // and list coherency traffic, but also tends to increase the
1366   // number of ObjectMonitors in circulation as well as the STW
1367   // scavenge costs.  As usual, we lean toward time in space-time
1368   // tradeoffs.
1369   const int MAXPRIVATE = 1024;
1370   NoSafepointVerifier nsv;
1371 
1372   for (;;) {
1373     ObjectMonitor* m;
1374 
1375     // 1: try to allocate from the thread's local om_free_list.
1376     // Threads will attempt to allocate first from their local list, then
1377     // from the global list, and only after those attempts fail will the
1378     // thread attempt to instantiate new monitors. Thread-local free lists
1379     // improve allocation latency, as well as reducing coherency traffic
1380     // on the shared global list.
1381     m = take_from_start_of_om_free_list(self);
1382     if (m != NULL) {
1383       guarantee(m->object() == NULL, "invariant");
1384       m->set_allocation_state(ObjectMonitor::New);
1385       prepend_to_om_in_use_list(self, m);
1386       return m;
1387     }
1388 
1389     // 2: try to allocate from the global om_list_globals._free_list
1390     // If we're using thread-local free lists then try
1391     // to reprovision the caller's free list.
1392     if (Atomic::load(&om_list_globals._free_list) != NULL) {
1393       // Reprovision the thread's om_free_list.
1394       // Use bulk transfers to reduce the allocation rate and heat
1395       // on various locks.
1396       for (int i = self->om_free_provision; --i >= 0;) {
1397         ObjectMonitor* take = take_from_start_of_global_free_list();
1398         if (take == NULL) {
1399           break;  // No more are available.
1400         }
1401         guarantee(take->object() == NULL, "invariant");
1402         if (AsyncDeflateIdleMonitors) {
1403           // We allowed 3 field values to linger during async deflation.
1404           // Clear or restore them as appropriate.
1405           take->set_header(markWord::zero());
1406           // DEFLATER_MARKER is the only non-NULL value we should see here.
1407           take->try_set_owner_from(DEFLATER_MARKER, NULL);
1408           if (take->contentions() < 0) {
1409             // Add back max_jint to restore the contentions field to its
1410             // proper value.
1411             Atomic::add(&take->_contentions, max_jint);
1412 
1413 #ifdef ASSERT
1414             jint l_contentions = take->contentions();
1415 #endif
1416             assert(l_contentions >= 0, "must not be negative: l_contentions=%d, contentions=%d",
1417                    l_contentions, take->contentions());
1418           }
1419         }
1420         take->Recycle();
1421         // Since we're taking from the global free-list, take must be Free.
1422         // om_release() also sets the allocation state to Free because it
1423         // is called from other code paths.
1424         assert(take->is_free(), "invariant");
1425         om_release(self, take, false);
1426       }
1427       self->om_free_provision += 1 + (self->om_free_provision / 2);
1428       if (self->om_free_provision > MAXPRIVATE) self->om_free_provision = MAXPRIVATE;
1429       continue;
1430     }
1431 
1432     // 3: allocate a block of new ObjectMonitors
1433     // Both the local and global free lists are empty -- resort to malloc().
1434     // In the current implementation ObjectMonitors are TSM - immortal.
1435     // Ideally, we'd write "new ObjectMonitor[_BLOCKSIZE], but we want
1436     // each ObjectMonitor to start at the beginning of a cache line,
1437     // so we use align_up().
1438     // A better solution would be to use C++ placement-new.
1439     // BEWARE: As it stands currently, we don't run the ctors!
1440     assert(_BLOCKSIZE > 1, "invariant");
1441     size_t neededsize = sizeof(PaddedObjectMonitor) * _BLOCKSIZE;
1442     PaddedObjectMonitor* temp;
1443     size_t aligned_size = neededsize + (OM_CACHE_LINE_SIZE - 1);
1444     void* real_malloc_addr = NEW_C_HEAP_ARRAY(char, aligned_size, mtInternal);
1445     temp = (PaddedObjectMonitor*)align_up(real_malloc_addr, OM_CACHE_LINE_SIZE);
1446     (void)memset((void *) temp, 0, neededsize);
1447 
1448     // Format the block.
1449     // initialize the linked list, each monitor points to its next
1450     // forming the single linked free list, the very first monitor
1451     // will points to next block, which forms the block list.
1452     // The trick of using the 1st element in the block as g_block_list
1453     // linkage should be reconsidered.  A better implementation would
1454     // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; }
1455 
1456     for (int i = 1; i < _BLOCKSIZE; i++) {
1457       temp[i].set_next_om((ObjectMonitor*)&temp[i + 1]);
1458       assert(temp[i].is_free(), "invariant");
1459     }
1460 
1461     // terminate the last monitor as the end of list
1462     temp[_BLOCKSIZE - 1].set_next_om((ObjectMonitor*)NULL);
1463 
1464     // Element [0] is reserved for global list linkage
1465     temp[0].set_object(CHAINMARKER);
1466 
1467     // Consider carving out this thread's current request from the
1468     // block in hand.  This avoids some lock traffic and redundant
1469     // list activity.
1470 
1471     prepend_block_to_lists(temp);
1472   }
1473 }
1474 
1475 // Place "m" on the caller's private per-thread om_free_list.
1476 // In practice there's no need to clamp or limit the number of
1477 // monitors on a thread's om_free_list as the only non-allocation time
1478 // we'll call om_release() is to return a monitor to the free list after
1479 // a CAS attempt failed. This doesn't allow unbounded #s of monitors to
1480 // accumulate on a thread's free list.
1481 //
1482 // Key constraint: all ObjectMonitors on a thread's free list and the global
1483 // free list must have their object field set to null. This prevents the
1484 // scavenger -- deflate_monitor_list() or deflate_monitor_list_using_JT()
1485 // -- from reclaiming them while we are trying to release them.
1486 
1487 void ObjectSynchronizer::om_release(Thread* self, ObjectMonitor* m,
1488                                     bool from_per_thread_alloc) {
1489   guarantee(m->header().value() == 0, "invariant");
1490   guarantee(m->object() == NULL, "invariant");
1491   NoSafepointVerifier nsv;
1492 
1493   if ((m->is_busy() | m->_recursions) != 0) {
1494     stringStream ss;
1495     fatal("freeing in-use monitor: %s, recursions=" INTX_FORMAT,
1496           m->is_busy_to_string(&ss), m->_recursions);
1497   }
1498   m->set_allocation_state(ObjectMonitor::Free);
1499   // _next_om is used for both per-thread in-use and free lists so
1500   // we have to remove 'm' from the in-use list first (as needed).
1501   if (from_per_thread_alloc) {
1502     // Need to remove 'm' from om_in_use_list.
1503     ObjectMonitor* mid = NULL;
1504     ObjectMonitor* next = NULL;
1505 
1506     // This list walk can race with another list walker or with async
1507     // deflation so we have to worry about an ObjectMonitor being
1508     // removed from this list while we are walking it.
1509 
1510     // Lock the list head to avoid racing with another list walker
1511     // or with async deflation.
1512     if ((mid = get_list_head_locked(&self->om_in_use_list)) == NULL) {
1513       fatal("thread=" INTPTR_FORMAT " in-use list must not be empty.", p2i(self));
1514     }
1515     next = unmarked_next(mid);
1516     if (m == mid) {
1517       // First special case:
1518       // 'm' matches mid, is the list head and is locked. Switch the list
1519       // head to next which unlocks the list head, but leaves the extracted
1520       // mid locked:
1521       Atomic::store(&self->om_in_use_list, next);
1522     } else if (m == next) {
1523       // Second special case:
1524       // 'm' matches next after the list head and we already have the list
1525       // head locked so set mid to what we are extracting:
1526       mid = next;
1527       // Lock mid to prevent races with a list walker or an async
1528       // deflater thread that's ahead of us. The locked list head
1529       // prevents races from behind us.
1530       om_lock(mid);
1531       // Update next to what follows mid (if anything):
1532       next = unmarked_next(mid);
1533       // Switch next after the list head to new next which unlocks the
1534       // list head, but leaves the extracted mid locked:
1535       self->om_in_use_list->set_next_om(next);
1536     } else {
1537       // We have to search the list to find 'm'.
1538       guarantee(next != NULL, "thread=" INTPTR_FORMAT ": om_in_use_list=" INTPTR_FORMAT
1539                 " is too short.", p2i(self), p2i(self->om_in_use_list));
1540       // Our starting anchor is next after the list head which is the
1541       // last ObjectMonitor we checked:
1542       ObjectMonitor* anchor = next;
1543       // Lock anchor to prevent races with a list walker or an async
1544       // deflater thread that's ahead of us. The locked list head
1545       // prevents races from behind us.
1546       om_lock(anchor);
1547       om_unlock(mid);  // Unlock the list head now that anchor is locked.
1548       while ((mid = unmarked_next(anchor)) != NULL) {
1549         if (m == mid) {
1550           // We found 'm' on the per-thread in-use list so extract it.
1551           // Update next to what follows mid (if anything):
1552           next = unmarked_next(mid);
1553           // Switch next after the anchor to new next which unlocks the
1554           // anchor, but leaves the extracted mid locked:
1555           anchor->set_next_om(next);
1556           break;
1557         } else {
1558           // Lock the next anchor to prevent races with a list walker
1559           // or an async deflater thread that's ahead of us. The locked
1560           // current anchor prevents races from behind us.
1561           om_lock(mid);
1562           // Unlock current anchor now that next anchor is locked:
1563           om_unlock(anchor);
1564           anchor = mid;  // Advance to new anchor and try again.
1565         }
1566       }
1567     }
1568 
1569     if (mid == NULL) {
1570       // Reached end of the list and didn't find 'm' so:
1571       fatal("thread=" INTPTR_FORMAT " must find m=" INTPTR_FORMAT "on om_in_use_list="
1572             INTPTR_FORMAT, p2i(self), p2i(m), p2i(self->om_in_use_list));
1573     }
1574 
1575     // At this point mid is disconnected from the in-use list so
1576     // its lock no longer has any effects on the in-use list.
1577     Atomic::dec(&self->om_in_use_count);
1578     // Unlock mid, but leave the next value for any lagging list
1579     // walkers. It will get cleaned up when mid is prepended to
1580     // the thread's free list:
1581     om_unlock(mid);
1582   }
1583 
1584   prepend_to_om_free_list(self, m);
1585   guarantee(m->is_free(), "invariant");
1586 }
1587 
1588 // Return ObjectMonitors on a moribund thread's free and in-use
1589 // lists to the appropriate global lists. The ObjectMonitors on the
1590 // per-thread in-use list may still be in use by other threads.
1591 //
1592 // We currently call om_flush() from Threads::remove() before the
1593 // thread has been excised from the thread list and is no longer a
1594 // mutator. This means that om_flush() cannot run concurrently with
1595 // a safepoint and interleave with deflate_idle_monitors(). In
1596 // particular, this ensures that the thread's in-use monitors are
1597 // scanned by a GC safepoint, either via Thread::oops_do() (before
1598 // om_flush() is called) or via ObjectSynchronizer::oops_do() (after
1599 // om_flush() is called).
1600 //
1601 // With AsyncDeflateIdleMonitors, deflate_global_idle_monitors_using_JT()
1602 // and deflate_per_thread_idle_monitors_using_JT() (in another thread) can
1603 // run at the same time as om_flush() so we have to follow a careful
1604 // protocol to prevent list corruption.
1605 
1606 void ObjectSynchronizer::om_flush(Thread* self) {
1607   // Process the per-thread in-use list first to be consistent.
1608   int in_use_count = 0;
1609   ObjectMonitor* in_use_list = NULL;
1610   ObjectMonitor* in_use_tail = NULL;
1611   NoSafepointVerifier nsv;
1612 
1613   // This function can race with a list walker or with an async
1614   // deflater thread so we lock the list head to prevent confusion.
1615   // An async deflater thread checks to see if the target thread
1616   // is exiting, but if it has made it past that check before we
1617   // started exiting, then it is racing to get to the in-use list.
1618   if ((in_use_list = get_list_head_locked(&self->om_in_use_list)) != NULL) {
1619     // At this point, we have locked the in-use list head so a racing
1620     // thread cannot come in after us. However, a racing thread could
1621     // be ahead of us; we'll detect that and delay to let it finish.
1622     //
1623     // The thread is going away, however the ObjectMonitors on the
1624     // om_in_use_list may still be in-use by other threads. Link
1625     // them to in_use_tail, which will be linked into the global
1626     // in-use list (om_list_globals._in_use_list) below.
1627     //
1628     // Account for the in-use list head before the loop since it is
1629     // already locked (by this thread):
1630     in_use_tail = in_use_list;
1631     in_use_count++;
1632     for (ObjectMonitor* cur_om = unmarked_next(in_use_list); cur_om != NULL;) {
1633       if (is_locked(cur_om)) {
1634         // cur_om is locked so there must be a racing walker or async
1635         // deflater thread ahead of us so we'll give it a chance to finish.
1636         while (is_locked(cur_om)) {
1637           os::naked_short_sleep(1);
1638         }
1639         // Refetch the possibly changed next field and try again.
1640         cur_om = unmarked_next(in_use_tail);
1641         continue;
1642       }
1643       if (cur_om->is_free()) {
1644         // cur_om was deflated and the allocation state was changed
1645         // to Free while it was locked. We happened to see it just
1646         // after it was unlocked (and added to the free list).
1647         // Refetch the possibly changed next field and try again.
1648         cur_om = unmarked_next(in_use_tail);
1649         continue;
1650       }
1651       in_use_tail = cur_om;
1652       in_use_count++;
1653       cur_om = unmarked_next(cur_om);
1654     }
1655     guarantee(in_use_tail != NULL, "invariant");
1656     int l_om_in_use_count = Atomic::load(&self->om_in_use_count);
1657     ADIM_guarantee(l_om_in_use_count == in_use_count, "in-use counts don't match: "
1658                    "l_om_in_use_count=%d, in_use_count=%d", l_om_in_use_count, in_use_count);
1659     Atomic::store(&self->om_in_use_count, 0);
1660     // Clear the in-use list head (which also unlocks it):
1661     Atomic::store(&self->om_in_use_list, (ObjectMonitor*)NULL);
1662     om_unlock(in_use_list);
1663   }
1664 
1665   int free_count = 0;
1666   ObjectMonitor* free_list = NULL;
1667   ObjectMonitor* free_tail = NULL;
1668   // This function can race with a list walker thread so we lock the
1669   // list head to prevent confusion.
1670   if ((free_list = get_list_head_locked(&self->om_free_list)) != NULL) {
1671     // At this point, we have locked the free list head so a racing
1672     // thread cannot come in after us. However, a racing thread could
1673     // be ahead of us; we'll detect that and delay to let it finish.
1674     //
1675     // The thread is going away. Set 'free_tail' to the last per-thread free
1676     // monitor which will be linked to om_list_globals._free_list below.
1677     //
1678     // Account for the free list head before the loop since it is
1679     // already locked (by this thread):
1680     free_tail = free_list;
1681     free_count++;
1682     for (ObjectMonitor* s = unmarked_next(free_list); s != NULL; s = unmarked_next(s)) {
1683       if (is_locked(s)) {
1684         // s is locked so there must be a racing walker thread ahead
1685         // of us so we'll give it a chance to finish.
1686         while (is_locked(s)) {
1687           os::naked_short_sleep(1);
1688         }
1689       }
1690       free_tail = s;
1691       free_count++;
1692       guarantee(s->object() == NULL, "invariant");
1693       if (s->is_busy()) {
1694         stringStream ss;
1695         fatal("must be !is_busy: %s", s->is_busy_to_string(&ss));
1696       }
1697     }
1698     guarantee(free_tail != NULL, "invariant");
1699     int l_om_free_count = Atomic::load(&self->om_free_count);
1700     ADIM_guarantee(l_om_free_count == free_count, "free counts don't match: "
1701                    "l_om_free_count=%d, free_count=%d", l_om_free_count, free_count);
1702     Atomic::store(&self->om_free_count, 0);
1703     Atomic::store(&self->om_free_list, (ObjectMonitor*)NULL);
1704     om_unlock(free_list);
1705   }
1706 
1707   if (free_tail != NULL) {
1708     prepend_list_to_global_free_list(free_list, free_tail, free_count);
1709   }
1710 
1711   if (in_use_tail != NULL) {
1712     prepend_list_to_global_in_use_list(in_use_list, in_use_tail, in_use_count);
1713   }
1714 
1715   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1716   LogStreamHandle(Info, monitorinflation) lsh_info;
1717   LogStream* ls = NULL;
1718   if (log_is_enabled(Debug, monitorinflation)) {
1719     ls = &lsh_debug;
1720   } else if ((free_count != 0 || in_use_count != 0) &&
1721              log_is_enabled(Info, monitorinflation)) {
1722     ls = &lsh_info;
1723   }
1724   if (ls != NULL) {
1725     ls->print_cr("om_flush: jt=" INTPTR_FORMAT ", free_count=%d"
1726                  ", in_use_count=%d" ", om_free_provision=%d",
1727                  p2i(self), free_count, in_use_count, self->om_free_provision);
1728   }
1729 }
1730 
1731 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1732                                        const oop obj,
1733                                        ObjectSynchronizer::InflateCause cause) {
1734   assert(event != NULL, "invariant");
1735   assert(event->should_commit(), "invariant");
1736   event->set_monitorClass(obj->klass());
1737   event->set_address((uintptr_t)(void*)obj);
1738   event->set_cause((u1)cause);
1739   event->commit();
1740 }
1741 
1742 // Fast path code shared by multiple functions
1743 void ObjectSynchronizer::inflate_helper(oop obj) {
1744   markWord mark = obj->mark();
1745   if (mark.has_monitor()) {
1746     ObjectMonitor* monitor = mark.monitor();
1747     assert(ObjectSynchronizer::verify_objmon_isinpool(monitor), "monitor=" INTPTR_FORMAT " is invalid", p2i(monitor));
1748     markWord dmw = monitor->header();
1749     assert(dmw.is_neutral(), "sanity check: header=" INTPTR_FORMAT, dmw.value());
1750     return;
1751   }
1752   (void)inflate(Thread::current(), obj, inflate_cause_vm_internal);
1753 }
1754 
1755 ObjectMonitor* ObjectSynchronizer::inflate(Thread* self, oop object,
1756                                            const InflateCause cause) {
1757   // Inflate mutates the heap ...
1758   // Relaxing assertion for bug 6320749.
1759   assert(Universe::verify_in_progress() ||
1760          !SafepointSynchronize::is_at_safepoint(), "invariant");
1761 
1762   EventJavaMonitorInflate event;
1763 
1764   for (;;) {
1765     const markWord mark = object->mark();
1766     assert(!mark.has_bias_pattern(), "invariant");
1767 
1768     // The mark can be in one of the following states:
1769     // *  Inflated     - just return
1770     // *  Stack-locked - coerce it to inflated
1771     // *  INFLATING    - busy wait for conversion to complete
1772     // *  Neutral      - aggressively inflate the object.
1773     // *  BIASED       - Illegal.  We should never see this
1774 
1775     // CASE: inflated
1776     if (mark.has_monitor()) {
1777       ObjectMonitor* inf = mark.monitor();
1778       markWord dmw = inf->header();
1779       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
1780       assert(AsyncDeflateIdleMonitors || inf->object() == object, "invariant");
1781       assert(ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
1782       return inf;
1783     }
1784 
1785     // CASE: inflation in progress - inflating over a stack-lock.
1786     // Some other thread is converting from stack-locked to inflated.
1787     // Only that thread can complete inflation -- other threads must wait.
1788     // The INFLATING value is transient.
1789     // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
1790     // We could always eliminate polling by parking the thread on some auxiliary list.
1791     if (mark == markWord::INFLATING()) {
1792       read_stable_mark(object);
1793       continue;
1794     }
1795 
1796     // CASE: stack-locked
1797     // Could be stack-locked either by this thread or by some other thread.
1798     //
1799     // Note that we allocate the objectmonitor speculatively, _before_ attempting
1800     // to install INFLATING into the mark word.  We originally installed INFLATING,
1801     // allocated the objectmonitor, and then finally STed the address of the
1802     // objectmonitor into the mark.  This was correct, but artificially lengthened
1803     // the interval in which INFLATED appeared in the mark, thus increasing
1804     // the odds of inflation contention.
1805     //
1806     // We now use per-thread private objectmonitor free lists.
1807     // These list are reprovisioned from the global free list outside the
1808     // critical INFLATING...ST interval.  A thread can transfer
1809     // multiple objectmonitors en-mass from the global free list to its local free list.
1810     // This reduces coherency traffic and lock contention on the global free list.
1811     // Using such local free lists, it doesn't matter if the om_alloc() call appears
1812     // before or after the CAS(INFLATING) operation.
1813     // See the comments in om_alloc().
1814 
1815     LogStreamHandle(Trace, monitorinflation) lsh;
1816 
1817     if (mark.has_locker()) {
1818       ObjectMonitor* m = om_alloc(self);
1819       // Optimistically prepare the objectmonitor - anticipate successful CAS
1820       // We do this before the CAS in order to minimize the length of time
1821       // in which INFLATING appears in the mark.
1822       m->Recycle();
1823       m->_Responsible  = NULL;
1824       m->_SpinDuration = ObjectMonitor::Knob_SpinLimit;   // Consider: maintain by type/class
1825 
1826       markWord cmp = object->cas_set_mark(markWord::INFLATING(), mark);
1827       if (cmp != mark) {
1828         // om_release() will reset the allocation state from New to Free.
1829         om_release(self, m, true);
1830         continue;       // Interference -- just retry
1831       }
1832 
1833       // We've successfully installed INFLATING (0) into the mark-word.
1834       // This is the only case where 0 will appear in a mark-word.
1835       // Only the singular thread that successfully swings the mark-word
1836       // to 0 can perform (or more precisely, complete) inflation.
1837       //
1838       // Why do we CAS a 0 into the mark-word instead of just CASing the
1839       // mark-word from the stack-locked value directly to the new inflated state?
1840       // Consider what happens when a thread unlocks a stack-locked object.
1841       // It attempts to use CAS to swing the displaced header value from the
1842       // on-stack BasicLock back into the object header.  Recall also that the
1843       // header value (hash code, etc) can reside in (a) the object header, or
1844       // (b) a displaced header associated with the stack-lock, or (c) a displaced
1845       // header in an ObjectMonitor.  The inflate() routine must copy the header
1846       // value from the BasicLock on the owner's stack to the ObjectMonitor, all
1847       // the while preserving the hashCode stability invariants.  If the owner
1848       // decides to release the lock while the value is 0, the unlock will fail
1849       // and control will eventually pass from slow_exit() to inflate.  The owner
1850       // will then spin, waiting for the 0 value to disappear.   Put another way,
1851       // the 0 causes the owner to stall if the owner happens to try to
1852       // drop the lock (restoring the header from the BasicLock to the object)
1853       // while inflation is in-progress.  This protocol avoids races that might
1854       // would otherwise permit hashCode values to change or "flicker" for an object.
1855       // Critically, while object->mark is 0 mark.displaced_mark_helper() is stable.
1856       // 0 serves as a "BUSY" inflate-in-progress indicator.
1857 
1858 
1859       // fetch the displaced mark from the owner's stack.
1860       // The owner can't die or unwind past the lock while our INFLATING
1861       // object is in the mark.  Furthermore the owner can't complete
1862       // an unlock on the object, either.
1863       markWord dmw = mark.displaced_mark_helper();
1864       // Catch if the object's header is not neutral (not locked and
1865       // not marked is what we care about here).
1866       ADIM_guarantee(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
1867 
1868       // Setup monitor fields to proper values -- prepare the monitor
1869       m->set_header(dmw);
1870 
1871       // Optimization: if the mark.locker stack address is associated
1872       // with this thread we could simply set m->_owner = self.
1873       // Note that a thread can inflate an object
1874       // that it has stack-locked -- as might happen in wait() -- directly
1875       // with CAS.  That is, we can avoid the xchg-NULL .... ST idiom.
1876       if (AsyncDeflateIdleMonitors) {
1877         m->set_owner_from(NULL, DEFLATER_MARKER, mark.locker());
1878       } else {
1879         m->set_owner_from(NULL, mark.locker());
1880       }
1881       m->set_object(object);
1882       // TODO-FIXME: assert BasicLock->dhw != 0.
1883 
1884       // Must preserve store ordering. The monitor state must
1885       // be stable at the time of publishing the monitor address.
1886       guarantee(object->mark() == markWord::INFLATING(), "invariant");
1887       object->release_set_mark(markWord::encode(m));
1888 
1889       // Once ObjectMonitor is configured and the object is associated
1890       // with the ObjectMonitor, it is safe to allow async deflation:
1891       assert(m->is_new(), "freshly allocated monitor must be new");
1892       m->set_allocation_state(ObjectMonitor::Old);
1893 
1894       // Hopefully the performance counters are allocated on distinct cache lines
1895       // to avoid false sharing on MP systems ...
1896       OM_PERFDATA_OP(Inflations, inc());
1897       if (log_is_enabled(Trace, monitorinflation)) {
1898         ResourceMark rm(self);
1899         lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark="
1900                      INTPTR_FORMAT ", type='%s'", p2i(object),
1901                      object->mark().value(), object->klass()->external_name());
1902       }
1903       if (event.should_commit()) {
1904         post_monitor_inflate_event(&event, object, cause);
1905       }
1906       return m;
1907     }
1908 
1909     // CASE: neutral
1910     // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1911     // If we know we're inflating for entry it's better to inflate by swinging a
1912     // pre-locked ObjectMonitor pointer into the object header.   A successful
1913     // CAS inflates the object *and* confers ownership to the inflating thread.
1914     // In the current implementation we use a 2-step mechanism where we CAS()
1915     // to inflate and then CAS() again to try to swing _owner from NULL to self.
1916     // An inflateTry() method that we could call from enter() would be useful.
1917 
1918     // Catch if the object's header is not neutral (not locked and
1919     // not marked is what we care about here).
1920     ADIM_guarantee(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
1921     ObjectMonitor* m = om_alloc(self);
1922     // prepare m for installation - set monitor to initial state
1923     m->Recycle();
1924     m->set_header(mark);
1925     if (AsyncDeflateIdleMonitors) {
1926       // DEFLATER_MARKER is the only non-NULL value we should see here.
1927       m->try_set_owner_from(DEFLATER_MARKER, NULL);
1928     }
1929     m->set_object(object);
1930     m->_Responsible  = NULL;
1931     m->_SpinDuration = ObjectMonitor::Knob_SpinLimit;       // consider: keep metastats by type/class
1932 
1933     if (object->cas_set_mark(markWord::encode(m), mark) != mark) {
1934       m->set_header(markWord::zero());
1935       m->set_object(NULL);
1936       m->Recycle();
1937       // om_release() will reset the allocation state from New to Free.
1938       om_release(self, m, true);
1939       m = NULL;
1940       continue;
1941       // interference - the markword changed - just retry.
1942       // The state-transitions are one-way, so there's no chance of
1943       // live-lock -- "Inflated" is an absorbing state.
1944     }
1945 
1946     // Once the ObjectMonitor is configured and object is associated
1947     // with the ObjectMonitor, it is safe to allow async deflation:
1948     assert(m->is_new(), "freshly allocated monitor must be new");
1949     m->set_allocation_state(ObjectMonitor::Old);
1950 
1951     // Hopefully the performance counters are allocated on distinct
1952     // cache lines to avoid false sharing on MP systems ...
1953     OM_PERFDATA_OP(Inflations, inc());
1954     if (log_is_enabled(Trace, monitorinflation)) {
1955       ResourceMark rm(self);
1956       lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark="
1957                    INTPTR_FORMAT ", type='%s'", p2i(object),
1958                    object->mark().value(), object->klass()->external_name());
1959     }
1960     if (event.should_commit()) {
1961       post_monitor_inflate_event(&event, object, cause);
1962     }
1963     return m;
1964   }
1965 }
1966 
1967 
1968 // We maintain a list of in-use monitors for each thread.
1969 //
1970 // For safepoint based deflation:
1971 // deflate_thread_local_monitors() scans a single thread's in-use list, while
1972 // deflate_idle_monitors() scans only a global list of in-use monitors which
1973 // is populated only as a thread dies (see om_flush()).
1974 //
1975 // These operations are called at all safepoints, immediately after mutators
1976 // are stopped, but before any objects have moved. Collectively they traverse
1977 // the population of in-use monitors, deflating where possible. The scavenged
1978 // monitors are returned to the global monitor free list.
1979 //
1980 // Beware that we scavenge at *every* stop-the-world point. Having a large
1981 // number of monitors in-use could negatively impact performance. We also want
1982 // to minimize the total # of monitors in circulation, as they incur a small
1983 // footprint penalty.
1984 //
1985 // Perversely, the heap size -- and thus the STW safepoint rate --
1986 // typically drives the scavenge rate.  Large heaps can mean infrequent GC,
1987 // which in turn can mean large(r) numbers of ObjectMonitors in circulation.
1988 // This is an unfortunate aspect of this design.
1989 //
1990 // For async deflation:
1991 // If a special deflation request is made, then the safepoint based
1992 // deflation mechanism is used. Otherwise, an async deflation request
1993 // is registered with the ServiceThread and it is notified.
1994 
1995 void ObjectSynchronizer::do_safepoint_work(DeflateMonitorCounters* counters) {
1996   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1997 
1998   // The per-thread in-use lists are handled in
1999   // ParallelSPCleanupThreadClosure::do_thread().
2000 
2001   if (!AsyncDeflateIdleMonitors || is_special_deflation_requested()) {
2002     // Use the older mechanism for the global in-use list or if a
2003     // special deflation has been requested before the safepoint.
2004     ObjectSynchronizer::deflate_idle_monitors(counters);
2005     return;
2006   }
2007 
2008   log_debug(monitorinflation)("requesting async deflation of idle monitors.");
2009   // Request deflation of idle monitors by the ServiceThread:
2010   set_is_async_deflation_requested(true);
2011   MonitorLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
2012   ml.notify_all();
2013 
2014   if (log_is_enabled(Debug, monitorinflation)) {
2015     // exit_globals()'s call to audit_and_print_stats() is done
2016     // at the Info level and not at a safepoint.
2017     // For safepoint based deflation, audit_and_print_stats() is called
2018     // in ObjectSynchronizer::finish_deflate_idle_monitors() at the
2019     // Debug level at a safepoint.
2020     ObjectSynchronizer::audit_and_print_stats(false /* on_exit */);
2021   }
2022 }
2023 
2024 // Deflate a single monitor if not in-use
2025 // Return true if deflated, false if in-use
2026 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
2027                                          ObjectMonitor** free_head_p,
2028                                          ObjectMonitor** free_tail_p) {
2029   bool deflated;
2030   // Normal case ... The monitor is associated with obj.
2031   const markWord mark = obj->mark();
2032   guarantee(mark == markWord::encode(mid), "should match: mark="
2033             INTPTR_FORMAT ", encoded mid=" INTPTR_FORMAT, mark.value(),
2034             markWord::encode(mid).value());
2035   // Make sure that mark.monitor() and markWord::encode() agree:
2036   guarantee(mark.monitor() == mid, "should match: monitor()=" INTPTR_FORMAT
2037             ", mid=" INTPTR_FORMAT, p2i(mark.monitor()), p2i(mid));
2038   const markWord dmw = mid->header();
2039   guarantee(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
2040 
2041   if (mid->is_busy()) {
2042     // Easy checks are first - the ObjectMonitor is busy so no deflation.
2043     deflated = false;
2044   } else {
2045     // Deflate the monitor if it is no longer being used
2046     // It's idle - scavenge and return to the global free list
2047     // plain old deflation ...
2048     if (log_is_enabled(Trace, monitorinflation)) {
2049       ResourceMark rm;
2050       log_trace(monitorinflation)("deflate_monitor: "
2051                                   "object=" INTPTR_FORMAT ", mark="
2052                                   INTPTR_FORMAT ", type='%s'", p2i(obj),
2053                                   mark.value(), obj->klass()->external_name());
2054     }
2055 
2056     // Restore the header back to obj
2057     obj->release_set_mark(dmw);
2058     if (AsyncDeflateIdleMonitors) {
2059       // clear() expects the owner field to be NULL.
2060       // DEFLATER_MARKER is the only non-NULL value we should see here.
2061       mid->try_set_owner_from(DEFLATER_MARKER, NULL);
2062     }
2063     mid->clear();
2064 
2065     assert(mid->object() == NULL, "invariant: object=" INTPTR_FORMAT,
2066            p2i(mid->object()));
2067     assert(mid->is_free(), "invariant");
2068 
2069     // Move the deflated ObjectMonitor to the working free list
2070     // defined by free_head_p and free_tail_p.
2071     if (*free_head_p == NULL) *free_head_p = mid;
2072     if (*free_tail_p != NULL) {
2073       // We append to the list so the caller can use mid->_next_om
2074       // to fix the linkages in its context.
2075       ObjectMonitor* prevtail = *free_tail_p;
2076       // Should have been cleaned up by the caller:
2077       // Note: Should not have to lock prevtail here since we're at a
2078       // safepoint and ObjectMonitors on the local free list should
2079       // not be accessed in parallel.
2080 #ifdef ASSERT
2081       ObjectMonitor* l_next_om = prevtail->next_om();
2082 #endif
2083       assert(l_next_om == NULL, "must be NULL: _next_om=" INTPTR_FORMAT, p2i(l_next_om));
2084       prevtail->set_next_om(mid);
2085     }
2086     *free_tail_p = mid;
2087     // At this point, mid->_next_om still refers to its current
2088     // value and another ObjectMonitor's _next_om field still
2089     // refers to this ObjectMonitor. Those linkages have to be
2090     // cleaned up by the caller who has the complete context.
2091     deflated = true;
2092   }
2093   return deflated;
2094 }
2095 
2096 // Deflate the specified ObjectMonitor if not in-use using a JavaThread.
2097 // Returns true if it was deflated and false otherwise.
2098 //
2099 // The async deflation protocol sets owner to DEFLATER_MARKER and
2100 // makes contentions negative as signals to contending threads that
2101 // an async deflation is in progress. There are a number of checks
2102 // as part of the protocol to make sure that the calling thread has
2103 // not lost the race to a contending thread.
2104 //
2105 // The ObjectMonitor has been successfully async deflated when:
2106 // (owner == DEFLATER_MARKER && contentions < 0)
2107 // Contending threads that see those values know to retry their operation.
2108 //
2109 bool ObjectSynchronizer::deflate_monitor_using_JT(ObjectMonitor* mid,
2110                                                   ObjectMonitor** free_head_p,
2111                                                   ObjectMonitor** free_tail_p) {
2112   assert(AsyncDeflateIdleMonitors, "sanity check");
2113   assert(Thread::current()->is_Java_thread(), "precondition");
2114   // A newly allocated ObjectMonitor should not be seen here so we
2115   // avoid an endless inflate/deflate cycle.
2116   assert(mid->is_old(), "must be old: allocation_state=%d",
2117          (int) mid->allocation_state());
2118 
2119   if (mid->is_busy()) {
2120     // Easy checks are first - the ObjectMonitor is busy so no deflation.
2121     return false;
2122   }
2123 
2124   // Set a NULL owner to DEFLATER_MARKER to force any contending thread
2125   // through the slow path. This is just the first part of the async
2126   // deflation dance.
2127   if (mid->try_set_owner_from(NULL, DEFLATER_MARKER) != NULL) {
2128     // The owner field is no longer NULL so we lost the race since the
2129     // ObjectMonitor is now busy.
2130     return false;
2131   }
2132 
2133   if (mid->contentions() > 0 || mid->_waiters != 0) {
2134     // Another thread has raced to enter the ObjectMonitor after
2135     // mid->is_busy() above or has already entered and waited on
2136     // it which makes it busy so no deflation. Restore owner to
2137     // NULL if it is still DEFLATER_MARKER.
2138     mid->try_set_owner_from(DEFLATER_MARKER, NULL);
2139     return false;
2140   }
2141 
2142   // Make contentions negative to force any contending threads to
2143   // retry. This is the second part of the async deflation dance.
2144   if (Atomic::cmpxchg(&mid->_contentions, (jint)0, -max_jint) != 0) {
2145     // The contentions was no longer 0 so we lost the race since the
2146     // ObjectMonitor is now busy. Restore owner to NULL if it is
2147     // still DEFLATER_MARKER:
2148     mid->try_set_owner_from(DEFLATER_MARKER, NULL);
2149     return false;
2150   }
2151 
2152   // If owner is still DEFLATER_MARKER, then we have successfully
2153   // signaled any contending threads to retry.
2154   if (!mid->owner_is_DEFLATER_MARKER()) {
2155     // If it is not, then we have lost the race to an entering thread
2156     // and the ObjectMonitor is now busy. This is the third and final
2157     // part of the async deflation dance.
2158     // Note: This owner check solves the ABA problem with contentions
2159     // where another thread acquired the ObjectMonitor, finished
2160     // using it and restored contentions to zero.
2161 
2162     // Add back max_jint to restore the contentions field to its
2163     // proper value (which may not be what we saw above):
2164     Atomic::add(&mid->_contentions, max_jint);
2165 
2166 #ifdef ASSERT
2167     jint l_contentions = mid->contentions();
2168 #endif
2169     assert(l_contentions >= 0, "must not be negative: l_contentions=%d, contentions=%d",
2170            l_contentions, mid->contentions());
2171     return false;
2172   }
2173 
2174   // Sanity checks for the races:
2175   guarantee(mid->contentions() < 0, "must be negative: contentions=%d",
2176             mid->contentions());
2177   guarantee(mid->_waiters == 0, "must be 0: waiters=%d", mid->_waiters);
2178   guarantee(mid->_cxq == NULL, "must be no contending threads: cxq="
2179             INTPTR_FORMAT, p2i(mid->_cxq));
2180   guarantee(mid->_EntryList == NULL,
2181             "must be no entering threads: EntryList=" INTPTR_FORMAT,
2182             p2i(mid->_EntryList));
2183 
2184   const oop obj = (oop) mid->object();
2185   if (log_is_enabled(Trace, monitorinflation)) {
2186     ResourceMark rm;
2187     log_trace(monitorinflation)("deflate_monitor_using_JT: "
2188                                 "object=" INTPTR_FORMAT ", mark="
2189                                 INTPTR_FORMAT ", type='%s'",
2190                                 p2i(obj), obj->mark().value(),
2191                                 obj->klass()->external_name());
2192   }
2193 
2194   // Install the old mark word if nobody else has already done it.
2195   mid->install_displaced_markword_in_object(obj);
2196   mid->clear_using_JT();
2197 
2198   assert(mid->object() == NULL, "must be NULL: object=" INTPTR_FORMAT,
2199          p2i(mid->object()));
2200   assert(mid->is_free(), "must be free: allocation_state=%d",
2201          (int)mid->allocation_state());
2202 
2203   // Move the deflated ObjectMonitor to the working free list
2204   // defined by free_head_p and free_tail_p.
2205   if (*free_head_p == NULL) {
2206     // First one on the list.
2207     *free_head_p = mid;
2208   }
2209   if (*free_tail_p != NULL) {
2210     // We append to the list so the caller can use mid->_next_om
2211     // to fix the linkages in its context.
2212     ObjectMonitor* prevtail = *free_tail_p;
2213     // prevtail should have been cleaned up by the caller:
2214 #ifdef ASSERT
2215     ObjectMonitor* l_next_om = unmarked_next(prevtail);
2216 #endif
2217     assert(l_next_om == NULL, "must be NULL: _next_om=" INTPTR_FORMAT, p2i(l_next_om));
2218     om_lock(prevtail);
2219     prevtail->set_next_om(mid);  // prevtail now points to mid (and is unlocked)
2220   }
2221   *free_tail_p = mid;
2222 
2223   // At this point, mid->_next_om still refers to its current
2224   // value and another ObjectMonitor's _next_om field still
2225   // refers to this ObjectMonitor. Those linkages have to be
2226   // cleaned up by the caller who has the complete context.
2227 
2228   // We leave owner == DEFLATER_MARKER and contentions < 0
2229   // to force any racing threads to retry.
2230   return true;  // Success, ObjectMonitor has been deflated.
2231 }
2232 
2233 // Walk a given monitor list, and deflate idle monitors.
2234 // The given list could be a per-thread list or a global list.
2235 //
2236 // In the case of parallel processing of thread local monitor lists,
2237 // work is done by Threads::parallel_threads_do() which ensures that
2238 // each Java thread is processed by exactly one worker thread, and
2239 // thus avoid conflicts that would arise when worker threads would
2240 // process the same monitor lists concurrently.
2241 //
2242 // See also ParallelSPCleanupTask and
2243 // SafepointSynchronize::do_cleanup_tasks() in safepoint.cpp and
2244 // Threads::parallel_java_threads_do() in thread.cpp.
2245 int ObjectSynchronizer::deflate_monitor_list(ObjectMonitor** list_p,
2246                                              int* count_p,
2247                                              ObjectMonitor** free_head_p,
2248                                              ObjectMonitor** free_tail_p) {
2249   ObjectMonitor* cur_mid_in_use = NULL;
2250   ObjectMonitor* mid = NULL;
2251   ObjectMonitor* next = NULL;
2252   int deflated_count = 0;
2253 
2254   // This list walk executes at a safepoint and does not race with any
2255   // other list walkers.
2256 
2257   for (mid = Atomic::load(list_p); mid != NULL; mid = next) {
2258     next = unmarked_next(mid);
2259     oop obj = (oop) mid->object();
2260     if (obj != NULL && deflate_monitor(mid, obj, free_head_p, free_tail_p)) {
2261       // Deflation succeeded and already updated free_head_p and
2262       // free_tail_p as needed. Finish the move to the local free list
2263       // by unlinking mid from the global or per-thread in-use list.
2264       if (cur_mid_in_use == NULL) {
2265         // mid is the list head so switch the list head to next:
2266         Atomic::store(list_p, next);
2267       } else {
2268         // Switch cur_mid_in_use's next field to next:
2269         cur_mid_in_use->set_next_om(next);
2270       }
2271       // At this point mid is disconnected from the in-use list.
2272       deflated_count++;
2273       Atomic::dec(count_p);
2274       // mid is current tail in the free_head_p list so NULL terminate it:
2275       mid->set_next_om(NULL);
2276     } else {
2277       cur_mid_in_use = mid;
2278     }
2279   }
2280   return deflated_count;
2281 }
2282 
2283 // Walk a given ObjectMonitor list and deflate idle ObjectMonitors using
2284 // a JavaThread. Returns the number of deflated ObjectMonitors. The given
2285 // list could be a per-thread in-use list or the global in-use list.
2286 // If a safepoint has started, then we save state via saved_mid_in_use_p
2287 // and return to the caller to honor the safepoint.
2288 //
2289 int ObjectSynchronizer::deflate_monitor_list_using_JT(ObjectMonitor** list_p,
2290                                                       int* count_p,
2291                                                       ObjectMonitor** free_head_p,
2292                                                       ObjectMonitor** free_tail_p,
2293                                                       ObjectMonitor** saved_mid_in_use_p) {
2294   assert(AsyncDeflateIdleMonitors, "sanity check");
2295   JavaThread* self = JavaThread::current();
2296 
2297   ObjectMonitor* cur_mid_in_use = NULL;
2298   ObjectMonitor* mid = NULL;
2299   ObjectMonitor* next = NULL;
2300   ObjectMonitor* next_next = NULL;
2301   int deflated_count = 0;
2302   NoSafepointVerifier nsv;
2303 
2304   // We use the more complicated lock-cur_mid_in_use-and-mid-as-we-go
2305   // protocol because om_release() can do list deletions in parallel;
2306   // this also prevents races with a list walker thread. We also
2307   // lock-next-next-as-we-go to prevent an om_flush() that is behind
2308   // this thread from passing us.
2309   if (*saved_mid_in_use_p == NULL) {
2310     // No saved state so start at the beginning.
2311     // Lock the list head so we can possibly deflate it:
2312     if ((mid = get_list_head_locked(list_p)) == NULL) {
2313       return 0;  // The list is empty so nothing to deflate.
2314     }
2315     next = unmarked_next(mid);
2316   } else {
2317     // We're restarting after a safepoint so restore the necessary state
2318     // before we resume.
2319     cur_mid_in_use = *saved_mid_in_use_p;
2320     // Lock cur_mid_in_use so we can possibly update its
2321     // next field to extract a deflated ObjectMonitor.
2322     om_lock(cur_mid_in_use);
2323     mid = unmarked_next(cur_mid_in_use);
2324     if (mid == NULL) {
2325       om_unlock(cur_mid_in_use);
2326       *saved_mid_in_use_p = NULL;
2327       return 0;  // The remainder is empty so nothing more to deflate.
2328     }
2329     // Lock mid so we can possibly deflate it:
2330     om_lock(mid);
2331     next = unmarked_next(mid);
2332   }
2333 
2334   while (true) {
2335     // The current mid is locked at this point. If we have a
2336     // cur_mid_in_use, then it is also locked at this point.
2337 
2338     if (next != NULL) {
2339       // We lock next so that an om_flush() thread that is behind us
2340       // cannot pass us when we unlock the current mid.
2341       om_lock(next);
2342       next_next = unmarked_next(next);
2343     }
2344 
2345     // Only try to deflate if there is an associated Java object and if
2346     // mid is old (is not newly allocated and is not newly freed).
2347     if (mid->object() != NULL && mid->is_old() &&
2348         deflate_monitor_using_JT(mid, free_head_p, free_tail_p)) {
2349       // Deflation succeeded and already updated free_head_p and
2350       // free_tail_p as needed. Finish the move to the local free list
2351       // by unlinking mid from the global or per-thread in-use list.
2352       if (cur_mid_in_use == NULL) {
2353         // mid is the list head and it is locked. Switch the list head
2354         // to next which is also locked (if not NULL) and also leave
2355         // mid locked:
2356         Atomic::store(list_p, next);
2357       } else {
2358         ObjectMonitor* locked_next = mark_om_ptr(next);
2359         // mid and cur_mid_in_use are locked. Switch cur_mid_in_use's
2360         // next field to locked_next and also leave mid locked:
2361         cur_mid_in_use->set_next_om(locked_next);
2362       }
2363       // At this point mid is disconnected from the in-use list so
2364       // its lock longer has any effects on in-use list.
2365       deflated_count++;
2366       Atomic::dec(count_p);
2367       // mid is current tail in the free_head_p list so NULL terminate it
2368       // (which also unlocks it):
2369       mid->set_next_om(NULL);
2370 
2371       // All the list management is done so move on to the next one:
2372       mid = next;  // mid keeps non-NULL next's locked state
2373       next = next_next;
2374     } else {
2375       // mid is considered in-use if it does not have an associated
2376       // Java object or mid is not old or deflation did not succeed.
2377       // A mid->is_new() node can be seen here when it is freshly
2378       // returned by om_alloc() (and skips the deflation code path).
2379       // A mid->is_old() node can be seen here when deflation failed.
2380       // A mid->is_free() node can be seen here when a fresh node from
2381       // om_alloc() is released by om_release() due to losing the race
2382       // in inflate().
2383 
2384       // All the list management is done so move on to the next one:
2385       if (cur_mid_in_use != NULL) {
2386         om_unlock(cur_mid_in_use);
2387       }
2388       // The next cur_mid_in_use keeps mid's lock state so
2389       // that it is stable for a possible next field change. It
2390       // cannot be modified by om_release() while it is locked.
2391       cur_mid_in_use = mid;
2392       mid = next;  // mid keeps non-NULL next's locked state
2393       next = next_next;
2394 
2395       if (SafepointMechanism::should_block(self) &&
2396           cur_mid_in_use != Atomic::load(list_p) && cur_mid_in_use->is_old()) {
2397         // If a safepoint has started and cur_mid_in_use is not the list
2398         // head and is old, then it is safe to use as saved state. Return
2399         // to the caller before blocking.
2400         *saved_mid_in_use_p = cur_mid_in_use;
2401         om_unlock(cur_mid_in_use);
2402         if (mid != NULL) {
2403           om_unlock(mid);
2404         }
2405         return deflated_count;
2406       }
2407     }
2408     if (mid == NULL) {
2409       if (cur_mid_in_use != NULL) {
2410         om_unlock(cur_mid_in_use);
2411       }
2412       break;  // Reached end of the list so nothing more to deflate.
2413     }
2414 
2415     // The current mid's next field is locked at this point. If we have
2416     // a cur_mid_in_use, then it is also locked at this point.
2417   }
2418   // We finished the list without a safepoint starting so there's
2419   // no need to save state.
2420   *saved_mid_in_use_p = NULL;
2421   return deflated_count;
2422 }
2423 
2424 void ObjectSynchronizer::prepare_deflate_idle_monitors(DeflateMonitorCounters* counters) {
2425   counters->n_in_use = 0;              // currently associated with objects
2426   counters->n_in_circulation = 0;      // extant
2427   counters->n_scavenged = 0;           // reclaimed (global and per-thread)
2428   counters->per_thread_scavenged = 0;  // per-thread scavenge total
2429   counters->per_thread_times = 0.0;    // per-thread scavenge times
2430 }
2431 
2432 void ObjectSynchronizer::deflate_idle_monitors(DeflateMonitorCounters* counters) {
2433   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2434 
2435   if (AsyncDeflateIdleMonitors) {
2436     // Nothing to do when global idle ObjectMonitors are deflated using
2437     // a JavaThread unless a special deflation has been requested.
2438     if (!is_special_deflation_requested()) {
2439       return;
2440     }
2441   }
2442 
2443   bool deflated = false;
2444 
2445   ObjectMonitor* free_head_p = NULL;  // Local SLL of scavenged monitors
2446   ObjectMonitor* free_tail_p = NULL;
2447   elapsedTimer timer;
2448 
2449   if (log_is_enabled(Info, monitorinflation)) {
2450     timer.start();
2451   }
2452 
2453   // Note: the thread-local monitors lists get deflated in
2454   // a separate pass. See deflate_thread_local_monitors().
2455 
2456   // For moribund threads, scan om_list_globals._in_use_list
2457   int deflated_count = 0;
2458   if (Atomic::load(&om_list_globals._in_use_list) != NULL) {
2459     // Update n_in_circulation before om_list_globals._in_use_count is
2460     // updated by deflation.
2461     Atomic::add(&counters->n_in_circulation,
2462                 Atomic::load(&om_list_globals._in_use_count));
2463 
2464     deflated_count = deflate_monitor_list(&om_list_globals._in_use_list,
2465                                           &om_list_globals._in_use_count,
2466                                           &free_head_p, &free_tail_p);
2467     Atomic::add(&counters->n_in_use, Atomic::load(&om_list_globals._in_use_count));
2468   }
2469 
2470   if (free_head_p != NULL) {
2471     // Move the deflated ObjectMonitors back to the global free list.
2472     guarantee(free_tail_p != NULL && deflated_count > 0, "invariant");
2473 #ifdef ASSERT
2474     ObjectMonitor* l_next_om = free_tail_p->next_om();
2475 #endif
2476     assert(l_next_om == NULL, "must be NULL: _next_om=" INTPTR_FORMAT, p2i(l_next_om));
2477     prepend_list_to_global_free_list(free_head_p, free_tail_p, deflated_count);
2478     Atomic::add(&counters->n_scavenged, deflated_count);
2479   }
2480   timer.stop();
2481 
2482   LogStreamHandle(Debug, monitorinflation) lsh_debug;
2483   LogStreamHandle(Info, monitorinflation) lsh_info;
2484   LogStream* ls = NULL;
2485   if (log_is_enabled(Debug, monitorinflation)) {
2486     ls = &lsh_debug;
2487   } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
2488     ls = &lsh_info;
2489   }
2490   if (ls != NULL) {
2491     ls->print_cr("deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count);
2492   }
2493 }
2494 
2495 class HandshakeForDeflation : public HandshakeClosure {
2496  public:
2497   HandshakeForDeflation() : HandshakeClosure("HandshakeForDeflation") {}
2498 
2499   void do_thread(Thread* thread) {
2500     log_trace(monitorinflation)("HandshakeForDeflation::do_thread: thread="
2501                                 INTPTR_FORMAT, p2i(thread));
2502   }
2503 };
2504 
2505 void ObjectSynchronizer::deflate_idle_monitors_using_JT() {
2506   assert(AsyncDeflateIdleMonitors, "sanity check");
2507 
2508   // Deflate any global idle monitors.
2509   deflate_global_idle_monitors_using_JT();
2510 
2511   int count = 0;
2512   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2513     if (Atomic::load(&jt->om_in_use_count) > 0 && !jt->is_exiting()) {
2514       // This JavaThread is using ObjectMonitors so deflate any that
2515       // are idle unless this JavaThread is exiting; do not race with
2516       // ObjectSynchronizer::om_flush().
2517       deflate_per_thread_idle_monitors_using_JT(jt);
2518       count++;
2519     }
2520   }
2521   if (count > 0) {
2522     log_debug(monitorinflation)("did async deflation of idle monitors for %d thread(s).", count);
2523   }
2524 
2525   log_info(monitorinflation)("async global_population=%d, global_in_use_count=%d, "
2526                              "global_free_count=%d, global_wait_count=%d",
2527                              Atomic::load(&om_list_globals._population),
2528                              Atomic::load(&om_list_globals._in_use_count),
2529                              Atomic::load(&om_list_globals._free_count),
2530                              Atomic::load(&om_list_globals._wait_count));
2531 
2532   // The ServiceThread's async deflation request has been processed.
2533   set_is_async_deflation_requested(false);
2534 
2535   if (Atomic::load(&om_list_globals._wait_count) > 0) {
2536     // There are deflated ObjectMonitors waiting for a handshake
2537     // (or a safepoint) for safety.
2538 
2539     ObjectMonitor* list = Atomic::load(&om_list_globals._wait_list);
2540     ADIM_guarantee(list != NULL, "om_list_globals._wait_list must not be NULL");
2541     int count = Atomic::load(&om_list_globals._wait_count);
2542     Atomic::store(&om_list_globals._wait_count, 0);
2543     Atomic::store(&om_list_globals._wait_list, (ObjectMonitor*)NULL);
2544 
2545     // Find the tail for prepend_list_to_common(). No need to mark
2546     // ObjectMonitors for this list walk since only the deflater
2547     // thread manages the wait list.
2548     int l_count = 0;
2549     ObjectMonitor* tail = NULL;
2550     for (ObjectMonitor* n = list; n != NULL; n = unmarked_next(n)) {
2551       tail = n;
2552       l_count++;
2553     }
2554     ADIM_guarantee(count == l_count, "count=%d != l_count=%d", count, l_count);
2555 
2556     // Will execute a safepoint if !ThreadLocalHandshakes:
2557     HandshakeForDeflation hfd_hc;
2558     Handshake::execute(&hfd_hc);
2559 
2560     prepend_list_to_common(list, tail, count, &om_list_globals._free_list,
2561                            &om_list_globals._free_count);
2562 
2563     log_info(monitorinflation)("moved %d idle monitors from global waiting list to global free list", count);
2564   }
2565 }
2566 
2567 // Deflate global idle ObjectMonitors using a JavaThread.
2568 //
2569 void ObjectSynchronizer::deflate_global_idle_monitors_using_JT() {
2570   assert(AsyncDeflateIdleMonitors, "sanity check");
2571   assert(Thread::current()->is_Java_thread(), "precondition");
2572   JavaThread* self = JavaThread::current();
2573 
2574   deflate_common_idle_monitors_using_JT(true /* is_global */, self);
2575 }
2576 
2577 // Deflate the specified JavaThread's idle ObjectMonitors using a JavaThread.
2578 //
2579 void ObjectSynchronizer::deflate_per_thread_idle_monitors_using_JT(JavaThread* target) {
2580   assert(AsyncDeflateIdleMonitors, "sanity check");
2581   assert(Thread::current()->is_Java_thread(), "precondition");
2582 
2583   deflate_common_idle_monitors_using_JT(false /* !is_global */, target);
2584 }
2585 
2586 // Deflate global or per-thread idle ObjectMonitors using a JavaThread.
2587 //
2588 void ObjectSynchronizer::deflate_common_idle_monitors_using_JT(bool is_global, JavaThread* target) {
2589   JavaThread* self = JavaThread::current();
2590 
2591   int deflated_count = 0;
2592   ObjectMonitor* free_head_p = NULL;  // Local SLL of scavenged ObjectMonitors
2593   ObjectMonitor* free_tail_p = NULL;
2594   ObjectMonitor* saved_mid_in_use_p = NULL;
2595   elapsedTimer timer;
2596 
2597   if (log_is_enabled(Info, monitorinflation)) {
2598     timer.start();
2599   }
2600 
2601   if (is_global) {
2602     OM_PERFDATA_OP(MonExtant, set_value(Atomic::load(&om_list_globals._in_use_count)));
2603   } else {
2604     OM_PERFDATA_OP(MonExtant, inc(Atomic::load(&target->om_in_use_count)));
2605   }
2606 
2607   do {
2608     int local_deflated_count;
2609     if (is_global) {
2610       local_deflated_count =
2611           deflate_monitor_list_using_JT(&om_list_globals._in_use_list,
2612                                         &om_list_globals._in_use_count,
2613                                         &free_head_p, &free_tail_p,
2614                                         &saved_mid_in_use_p);
2615     } else {
2616       local_deflated_count =
2617           deflate_monitor_list_using_JT(&target->om_in_use_list,
2618                                         &target->om_in_use_count, &free_head_p,
2619                                         &free_tail_p, &saved_mid_in_use_p);
2620     }
2621     deflated_count += local_deflated_count;
2622 
2623     if (free_head_p != NULL) {
2624       // Move the deflated ObjectMonitors to the global free list.
2625       guarantee(free_tail_p != NULL && local_deflated_count > 0, "free_tail_p=" INTPTR_FORMAT ", local_deflated_count=%d", p2i(free_tail_p), local_deflated_count);
2626       // Note: The target thread can be doing an om_alloc() that
2627       // is trying to prepend an ObjectMonitor on its in-use list
2628       // at the same time that we have deflated the current in-use
2629       // list head and put it on the local free list. prepend_to_common()
2630       // will detect the race and retry which avoids list corruption,
2631       // but the next field in free_tail_p can flicker to marked
2632       // and then unmarked while prepend_to_common() is sorting it
2633       // all out.
2634 #ifdef ASSERT
2635       ObjectMonitor* l_next_om = unmarked_next(free_tail_p);
2636 #endif
2637       assert(l_next_om == NULL, "must be NULL: _next_om=" INTPTR_FORMAT, p2i(l_next_om));
2638 
2639       prepend_list_to_global_wait_list(free_head_p, free_tail_p, local_deflated_count);
2640 
2641       OM_PERFDATA_OP(Deflations, inc(local_deflated_count));
2642     }
2643 
2644     if (saved_mid_in_use_p != NULL) {
2645       // deflate_monitor_list_using_JT() detected a safepoint starting.
2646       timer.stop();
2647       {
2648         if (is_global) {
2649           log_debug(monitorinflation)("pausing deflation of global idle monitors for a safepoint.");
2650         } else {
2651           log_debug(monitorinflation)("jt=" INTPTR_FORMAT ": pausing deflation of per-thread idle monitors for a safepoint.", p2i(target));
2652         }
2653         assert(SafepointMechanism::should_block(self), "sanity check");
2654         ThreadBlockInVM blocker(self);
2655       }
2656       // Prepare for another loop after the safepoint.
2657       free_head_p = NULL;
2658       free_tail_p = NULL;
2659       if (log_is_enabled(Info, monitorinflation)) {
2660         timer.start();
2661       }
2662     }
2663   } while (saved_mid_in_use_p != NULL);
2664   timer.stop();
2665 
2666   LogStreamHandle(Debug, monitorinflation) lsh_debug;
2667   LogStreamHandle(Info, monitorinflation) lsh_info;
2668   LogStream* ls = NULL;
2669   if (log_is_enabled(Debug, monitorinflation)) {
2670     ls = &lsh_debug;
2671   } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
2672     ls = &lsh_info;
2673   }
2674   if (ls != NULL) {
2675     if (is_global) {
2676       ls->print_cr("async-deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count);
2677     } else {
2678       ls->print_cr("jt=" INTPTR_FORMAT ": async-deflating per-thread idle monitors, %3.7f secs, %d monitors", p2i(target), timer.seconds(), deflated_count);
2679     }
2680   }
2681 }
2682 
2683 void ObjectSynchronizer::finish_deflate_idle_monitors(DeflateMonitorCounters* counters) {
2684   // Report the cumulative time for deflating each thread's idle
2685   // monitors. Note: if the work is split among more than one
2686   // worker thread, then the reported time will likely be more
2687   // than a beginning to end measurement of the phase.
2688   log_info(safepoint, cleanup)("deflating per-thread idle monitors, %3.7f secs, monitors=%d", counters->per_thread_times, counters->per_thread_scavenged);
2689 
2690   bool needs_special_deflation = is_special_deflation_requested();
2691   if (AsyncDeflateIdleMonitors && !needs_special_deflation) {
2692     // Nothing to do when idle ObjectMonitors are deflated using
2693     // a JavaThread unless a special deflation has been requested.
2694     return;
2695   }
2696 
2697   if (log_is_enabled(Debug, monitorinflation)) {
2698     // exit_globals()'s call to audit_and_print_stats() is done
2699     // at the Info level and not at a safepoint.
2700     // For async deflation, audit_and_print_stats() is called in
2701     // ObjectSynchronizer::do_safepoint_work() at the Debug level
2702     // at a safepoint.
2703     ObjectSynchronizer::audit_and_print_stats(false /* on_exit */);
2704   } else if (log_is_enabled(Info, monitorinflation)) {
2705     log_info(monitorinflation)("global_population=%d, global_in_use_count=%d, "
2706                                "global_free_count=%d, global_wait_count=%d",
2707                                Atomic::load(&om_list_globals._population),
2708                                Atomic::load(&om_list_globals._in_use_count),
2709                                Atomic::load(&om_list_globals._free_count),
2710                                Atomic::load(&om_list_globals._wait_count));
2711   }
2712 
2713   OM_PERFDATA_OP(Deflations, inc(counters->n_scavenged));
2714   OM_PERFDATA_OP(MonExtant, set_value(counters->n_in_circulation));
2715 
2716   GVars.stw_random = os::random();
2717   GVars.stw_cycle++;
2718 
2719   if (needs_special_deflation) {
2720     set_is_special_deflation_requested(false);  // special deflation is done
2721   }
2722 }
2723 
2724 void ObjectSynchronizer::deflate_thread_local_monitors(Thread* thread, DeflateMonitorCounters* counters) {
2725   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2726 
2727   if (AsyncDeflateIdleMonitors && !is_special_deflation_requested()) {
2728     // Nothing to do if a special deflation has NOT been requested.
2729     return;
2730   }
2731 
2732   ObjectMonitor* free_head_p = NULL;  // Local SLL of scavenged monitors
2733   ObjectMonitor* free_tail_p = NULL;
2734   elapsedTimer timer;
2735 
2736   if (log_is_enabled(Info, safepoint, cleanup) ||
2737       log_is_enabled(Info, monitorinflation)) {
2738     timer.start();
2739   }
2740 
2741   // Update n_in_circulation before om_in_use_count is updated by deflation.
2742   Atomic::add(&counters->n_in_circulation, Atomic::load(&thread->om_in_use_count));
2743 
2744   int deflated_count = deflate_monitor_list(&thread->om_in_use_list, &thread->om_in_use_count, &free_head_p, &free_tail_p);
2745   Atomic::add(&counters->n_in_use, Atomic::load(&thread->om_in_use_count));
2746 
2747   if (free_head_p != NULL) {
2748     // Move the deflated ObjectMonitors back to the global free list.
2749     guarantee(free_tail_p != NULL && deflated_count > 0, "invariant");
2750 #ifdef ASSERT
2751     ObjectMonitor* l_next_om = free_tail_p->next_om();
2752 #endif
2753     assert(l_next_om == NULL, "must be NULL: _next_om=" INTPTR_FORMAT, p2i(l_next_om));
2754     prepend_list_to_global_free_list(free_head_p, free_tail_p, deflated_count);
2755     Atomic::add(&counters->n_scavenged, deflated_count);
2756     Atomic::add(&counters->per_thread_scavenged, deflated_count);
2757   }
2758 
2759   timer.stop();
2760   counters->per_thread_times += timer.seconds();
2761 
2762   LogStreamHandle(Debug, monitorinflation) lsh_debug;
2763   LogStreamHandle(Info, monitorinflation) lsh_info;
2764   LogStream* ls = NULL;
2765   if (log_is_enabled(Debug, monitorinflation)) {
2766     ls = &lsh_debug;
2767   } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
2768     ls = &lsh_info;
2769   }
2770   if (ls != NULL) {
2771     ls->print_cr("jt=" INTPTR_FORMAT ": deflating per-thread idle monitors, %3.7f secs, %d monitors", p2i(thread), timer.seconds(), deflated_count);
2772   }
2773 }
2774 
2775 // Monitor cleanup on JavaThread::exit
2776 
2777 // Iterate through monitor cache and attempt to release thread's monitors
2778 // Gives up on a particular monitor if an exception occurs, but continues
2779 // the overall iteration, swallowing the exception.
2780 class ReleaseJavaMonitorsClosure: public MonitorClosure {
2781  private:
2782   TRAPS;
2783 
2784  public:
2785   ReleaseJavaMonitorsClosure(Thread* thread) : THREAD(thread) {}
2786   void do_monitor(ObjectMonitor* mid) {
2787     if (mid->owner() == THREAD) {
2788       (void)mid->complete_exit(CHECK);
2789     }
2790   }
2791 };
2792 
2793 // Release all inflated monitors owned by THREAD.  Lightweight monitors are
2794 // ignored.  This is meant to be called during JNI thread detach which assumes
2795 // all remaining monitors are heavyweight.  All exceptions are swallowed.
2796 // Scanning the extant monitor list can be time consuming.
2797 // A simple optimization is to add a per-thread flag that indicates a thread
2798 // called jni_monitorenter() during its lifetime.
2799 //
2800 // Instead of No_Savepoint_Verifier it might be cheaper to
2801 // use an idiom of the form:
2802 //   auto int tmp = SafepointSynchronize::_safepoint_counter ;
2803 //   <code that must not run at safepoint>
2804 //   guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
2805 // Since the tests are extremely cheap we could leave them enabled
2806 // for normal product builds.
2807 
2808 void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) {
2809   assert(THREAD == JavaThread::current(), "must be current Java thread");
2810   NoSafepointVerifier nsv;
2811   ReleaseJavaMonitorsClosure rjmc(THREAD);
2812   ObjectSynchronizer::monitors_iterate(&rjmc);
2813   THREAD->clear_pending_exception();
2814 }
2815 
2816 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) {
2817   switch (cause) {
2818     case inflate_cause_vm_internal:    return "VM Internal";
2819     case inflate_cause_monitor_enter:  return "Monitor Enter";
2820     case inflate_cause_wait:           return "Monitor Wait";
2821     case inflate_cause_notify:         return "Monitor Notify";
2822     case inflate_cause_hash_code:      return "Monitor Hash Code";
2823     case inflate_cause_jni_enter:      return "JNI Monitor Enter";
2824     case inflate_cause_jni_exit:       return "JNI Monitor Exit";
2825     default:
2826       ShouldNotReachHere();
2827   }
2828   return "Unknown";
2829 }
2830 
2831 //------------------------------------------------------------------------------
2832 // Debugging code
2833 
2834 u_char* ObjectSynchronizer::get_gvars_addr() {
2835   return (u_char*)&GVars;
2836 }
2837 
2838 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() {
2839   return (u_char*)&GVars.hc_sequence;
2840 }
2841 
2842 size_t ObjectSynchronizer::get_gvars_size() {
2843   return sizeof(SharedGlobals);
2844 }
2845 
2846 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() {
2847   return (u_char*)&GVars.stw_random;
2848 }
2849 
2850 // This function can be called at a safepoint or it can be called when
2851 // we are trying to exit the VM. When we are trying to exit the VM, the
2852 // list walker functions can run in parallel with the other list
2853 // operations so spin-locking is used for safety.
2854 //
2855 // Calls to this function can be added in various places as a debugging
2856 // aid; pass 'true' for the 'on_exit' parameter to have in-use monitor
2857 // details logged at the Info level and 'false' for the 'on_exit'
2858 // parameter to have in-use monitor details logged at the Trace level.
2859 // deflate_monitor_list() no longer uses spin-locking so be careful
2860 // when adding audit_and_print_stats() calls at a safepoint.
2861 //
2862 void ObjectSynchronizer::audit_and_print_stats(bool on_exit) {
2863   assert(on_exit || SafepointSynchronize::is_at_safepoint(), "invariant");
2864 
2865   LogStreamHandle(Debug, monitorinflation) lsh_debug;
2866   LogStreamHandle(Info, monitorinflation) lsh_info;
2867   LogStreamHandle(Trace, monitorinflation) lsh_trace;
2868   LogStream* ls = NULL;
2869   if (log_is_enabled(Trace, monitorinflation)) {
2870     ls = &lsh_trace;
2871   } else if (log_is_enabled(Debug, monitorinflation)) {
2872     ls = &lsh_debug;
2873   } else if (log_is_enabled(Info, monitorinflation)) {
2874     ls = &lsh_info;
2875   }
2876   assert(ls != NULL, "sanity check");
2877 
2878   // Log counts for the global and per-thread monitor lists:
2879   int chk_om_population = log_monitor_list_counts(ls);
2880   int error_cnt = 0;
2881 
2882   ls->print_cr("Checking global lists:");
2883 
2884   // Check om_list_globals._population:
2885   if (Atomic::load(&om_list_globals._population) == chk_om_population) {
2886     ls->print_cr("global_population=%d equals chk_om_population=%d",
2887                  Atomic::load(&om_list_globals._population), chk_om_population);
2888   } else {
2889     // With fine grained locks on the monitor lists, it is possible for
2890     // log_monitor_list_counts() to return a value that doesn't match
2891     // om_list_globals._population. So far a higher value has been
2892     // seen in testing so something is being double counted by
2893     // log_monitor_list_counts().
2894     ls->print_cr("WARNING: global_population=%d is not equal to "
2895                  "chk_om_population=%d",
2896                  Atomic::load(&om_list_globals._population), chk_om_population);
2897   }
2898 
2899   // Check om_list_globals._in_use_list and om_list_globals._in_use_count:
2900   chk_global_in_use_list_and_count(ls, &error_cnt);
2901 
2902   // Check om_list_globals._free_list and om_list_globals._free_count:
2903   chk_global_free_list_and_count(ls, &error_cnt);
2904 
2905   // Check om_list_globals._wait_list and om_list_globals._wait_count:
2906   chk_global_wait_list_and_count(ls, &error_cnt);
2907 
2908   ls->print_cr("Checking per-thread lists:");
2909 
2910   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2911     // Check om_in_use_list and om_in_use_count:
2912     chk_per_thread_in_use_list_and_count(jt, ls, &error_cnt);
2913 
2914     // Check om_free_list and om_free_count:
2915     chk_per_thread_free_list_and_count(jt, ls, &error_cnt);
2916   }
2917 
2918   if (error_cnt == 0) {
2919     ls->print_cr("No errors found in monitor list checks.");
2920   } else {
2921     log_error(monitorinflation)("found monitor list errors: error_cnt=%d", error_cnt);
2922   }
2923 
2924   if ((on_exit && log_is_enabled(Info, monitorinflation)) ||
2925       (!on_exit && log_is_enabled(Trace, monitorinflation))) {
2926     // When exiting this log output is at the Info level. When called
2927     // at a safepoint, this log output is at the Trace level since
2928     // there can be a lot of it.
2929     log_in_use_monitor_details(ls);
2930   }
2931 
2932   ls->flush();
2933 
2934   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
2935 }
2936 
2937 // Check a free monitor entry; log any errors.
2938 void ObjectSynchronizer::chk_free_entry(JavaThread* jt, ObjectMonitor* n,
2939                                         outputStream * out, int *error_cnt_p) {
2940   stringStream ss;
2941   if (n->is_busy()) {
2942     if (jt != NULL) {
2943       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2944                     ": free per-thread monitor must not be busy: %s", p2i(jt),
2945                     p2i(n), n->is_busy_to_string(&ss));
2946     } else {
2947       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2948                     "must not be busy: %s", p2i(n), n->is_busy_to_string(&ss));
2949     }
2950     *error_cnt_p = *error_cnt_p + 1;
2951   }
2952   if (n->header().value() != 0) {
2953     if (jt != NULL) {
2954       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2955                     ": free per-thread monitor must have NULL _header "
2956                     "field: _header=" INTPTR_FORMAT, p2i(jt), p2i(n),
2957                     n->header().value());
2958       *error_cnt_p = *error_cnt_p + 1;
2959     } else if (!AsyncDeflateIdleMonitors) {
2960       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2961                     "must have NULL _header field: _header=" INTPTR_FORMAT,
2962                     p2i(n), n->header().value());
2963       *error_cnt_p = *error_cnt_p + 1;
2964     }
2965   }
2966   if (n->object() != NULL) {
2967     if (jt != NULL) {
2968       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2969                     ": free per-thread monitor must have NULL _object "
2970                     "field: _object=" INTPTR_FORMAT, p2i(jt), p2i(n),
2971                     p2i(n->object()));
2972     } else {
2973       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2974                     "must have NULL _object field: _object=" INTPTR_FORMAT,
2975                     p2i(n), p2i(n->object()));
2976     }
2977     *error_cnt_p = *error_cnt_p + 1;
2978   }
2979 }
2980 
2981 // Lock the next ObjectMonitor for traversal and unlock the current
2982 // ObjectMonitor. Returns the next ObjectMonitor if there is one.
2983 // Otherwise returns NULL (after unlocking the current ObjectMonitor).
2984 // This function is used by the various list walker functions to
2985 // safely walk a list without allowing an ObjectMonitor to be moved
2986 // to another list in the middle of a walk.
2987 static ObjectMonitor* lock_next_for_traversal(ObjectMonitor* cur) {
2988   assert(is_locked(cur), "cur=" INTPTR_FORMAT " must be locked", p2i(cur));
2989   ObjectMonitor* next = unmarked_next(cur);
2990   if (next == NULL) {  // Reached the end of the list.
2991     om_unlock(cur);
2992     return NULL;
2993   }
2994   om_lock(next);   // Lock next before unlocking current to keep
2995   om_unlock(cur);  // from being by-passed by another thread.
2996   return next;
2997 }
2998 
2999 // Check the global free list and count; log the results of the checks.
3000 void ObjectSynchronizer::chk_global_free_list_and_count(outputStream * out,
3001                                                         int *error_cnt_p) {
3002   int chk_om_free_count = 0;
3003   ObjectMonitor* cur = NULL;
3004   if ((cur = get_list_head_locked(&om_list_globals._free_list)) != NULL) {
3005     // Marked the global free list head so process the list.
3006     while (true) {
3007       chk_free_entry(NULL /* jt */, cur, out, error_cnt_p);
3008       chk_om_free_count++;
3009 
3010       cur = lock_next_for_traversal(cur);
3011       if (cur == NULL) {
3012         break;
3013       }
3014     }
3015   }
3016   int l_free_count = Atomic::load(&om_list_globals._free_count);
3017   if (l_free_count == chk_om_free_count) {
3018     out->print_cr("global_free_count=%d equals chk_om_free_count=%d",
3019                   l_free_count, chk_om_free_count);
3020   } else {
3021     // With fine grained locks on om_list_globals._free_list, it
3022     // is possible for an ObjectMonitor to be prepended to
3023     // om_list_globals._free_list after we started calculating
3024     // chk_om_free_count so om_list_globals._free_count may not
3025     // match anymore.
3026     out->print_cr("WARNING: global_free_count=%d is not equal to "
3027                   "chk_om_free_count=%d", l_free_count, chk_om_free_count);
3028   }
3029 }
3030 
3031 // Check the global wait list and count; log the results of the checks.
3032 void ObjectSynchronizer::chk_global_wait_list_and_count(outputStream * out,
3033                                                         int *error_cnt_p) {
3034   int chk_om_wait_count = 0;
3035   ObjectMonitor* cur = NULL;
3036   if ((cur = get_list_head_locked(&om_list_globals._wait_list)) != NULL) {
3037     // Marked the global wait list head so process the list.
3038     while (true) {
3039       // Rules for om_list_globals._wait_list are the same as for
3040       // om_list_globals._free_list:
3041       chk_free_entry(NULL /* jt */, cur, out, error_cnt_p);
3042       chk_om_wait_count++;
3043 
3044       cur = lock_next_for_traversal(cur);
3045       if (cur == NULL) {
3046         break;
3047       }
3048     }
3049   }
3050   if (Atomic::load(&om_list_globals._wait_count) == chk_om_wait_count) {
3051     out->print_cr("global_wait_count=%d equals chk_om_wait_count=%d",
3052                   Atomic::load(&om_list_globals._wait_count), chk_om_wait_count);
3053   } else {
3054     out->print_cr("ERROR: global_wait_count=%d is not equal to "
3055                   "chk_om_wait_count=%d",
3056                   Atomic::load(&om_list_globals._wait_count), chk_om_wait_count);
3057     *error_cnt_p = *error_cnt_p + 1;
3058   }
3059 }
3060 
3061 // Check the global in-use list and count; log the results of the checks.
3062 void ObjectSynchronizer::chk_global_in_use_list_and_count(outputStream * out,
3063                                                           int *error_cnt_p) {
3064   int chk_om_in_use_count = 0;
3065   ObjectMonitor* cur = NULL;
3066   if ((cur = get_list_head_locked(&om_list_globals._in_use_list)) != NULL) {
3067     // Marked the global in-use list head so process the list.
3068     while (true) {
3069       chk_in_use_entry(NULL /* jt */, cur, out, error_cnt_p);
3070       chk_om_in_use_count++;
3071 
3072       cur = lock_next_for_traversal(cur);
3073       if (cur == NULL) {
3074         break;
3075       }
3076     }
3077   }
3078   int l_in_use_count = Atomic::load(&om_list_globals._in_use_count);
3079   if (l_in_use_count == chk_om_in_use_count) {
3080     out->print_cr("global_in_use_count=%d equals chk_om_in_use_count=%d",
3081                   l_in_use_count, chk_om_in_use_count);
3082   } else {
3083     // With fine grained locks on the monitor lists, it is possible for
3084     // an exiting JavaThread to put its in-use ObjectMonitors on the
3085     // global in-use list after chk_om_in_use_count is calculated above.
3086     out->print_cr("WARNING: global_in_use_count=%d is not equal to chk_om_in_use_count=%d",
3087                   l_in_use_count, chk_om_in_use_count);
3088   }
3089 }
3090 
3091 // Check an in-use monitor entry; log any errors.
3092 void ObjectSynchronizer::chk_in_use_entry(JavaThread* jt, ObjectMonitor* n,
3093                                           outputStream * out, int *error_cnt_p) {
3094   if (n->header().value() == 0) {
3095     if (jt != NULL) {
3096       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
3097                     ": in-use per-thread monitor must have non-NULL _header "
3098                     "field.", p2i(jt), p2i(n));
3099     } else {
3100       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global monitor "
3101                     "must have non-NULL _header field.", p2i(n));
3102     }
3103     *error_cnt_p = *error_cnt_p + 1;
3104   }
3105   if (n->object() == NULL) {
3106     if (jt != NULL) {
3107       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
3108                     ": in-use per-thread monitor must have non-NULL _object "
3109                     "field.", p2i(jt), p2i(n));
3110     } else {
3111       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global monitor "
3112                     "must have non-NULL _object field.", p2i(n));
3113     }
3114     *error_cnt_p = *error_cnt_p + 1;
3115   }
3116   const oop obj = (oop)n->object();
3117   const markWord mark = obj->mark();
3118   if (!mark.has_monitor()) {
3119     if (jt != NULL) {
3120       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
3121                     ": in-use per-thread monitor's object does not think "
3122                     "it has a monitor: obj=" INTPTR_FORMAT ", mark="
3123                     INTPTR_FORMAT,  p2i(jt), p2i(n), p2i(obj), mark.value());
3124     } else {
3125       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global "
3126                     "monitor's object does not think it has a monitor: obj="
3127                     INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n),
3128                     p2i(obj), mark.value());
3129     }
3130     *error_cnt_p = *error_cnt_p + 1;
3131   }
3132   ObjectMonitor* const obj_mon = mark.monitor();
3133   if (n != obj_mon) {
3134     if (jt != NULL) {
3135       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
3136                     ": in-use per-thread monitor's object does not refer "
3137                     "to the same monitor: obj=" INTPTR_FORMAT ", mark="
3138                     INTPTR_FORMAT ", obj_mon=" INTPTR_FORMAT, p2i(jt),
3139                     p2i(n), p2i(obj), mark.value(), p2i(obj_mon));
3140     } else {
3141       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global "
3142                     "monitor's object does not refer to the same monitor: obj="
3143                     INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon="
3144                     INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon));
3145     }
3146     *error_cnt_p = *error_cnt_p + 1;
3147   }
3148 }
3149 
3150 // Check the thread's free list and count; log the results of the checks.
3151 void ObjectSynchronizer::chk_per_thread_free_list_and_count(JavaThread *jt,
3152                                                             outputStream * out,
3153                                                             int *error_cnt_p) {
3154   int chk_om_free_count = 0;
3155   ObjectMonitor* cur = NULL;
3156   if ((cur = get_list_head_locked(&jt->om_free_list)) != NULL) {
3157     // Marked the per-thread free list head so process the list.
3158     while (true) {
3159       chk_free_entry(jt, cur, out, error_cnt_p);
3160       chk_om_free_count++;
3161 
3162       cur = lock_next_for_traversal(cur);
3163       if (cur == NULL) {
3164         break;
3165       }
3166     }
3167   }
3168   int l_om_free_count = Atomic::load(&jt->om_free_count);
3169   if (l_om_free_count == chk_om_free_count) {
3170     out->print_cr("jt=" INTPTR_FORMAT ": om_free_count=%d equals "
3171                   "chk_om_free_count=%d", p2i(jt), l_om_free_count, chk_om_free_count);
3172   } else {
3173     out->print_cr("ERROR: jt=" INTPTR_FORMAT ": om_free_count=%d is not "
3174                   "equal to chk_om_free_count=%d", p2i(jt), l_om_free_count,
3175                   chk_om_free_count);
3176     *error_cnt_p = *error_cnt_p + 1;
3177   }
3178 }
3179 
3180 // Check the thread's in-use list and count; log the results of the checks.
3181 void ObjectSynchronizer::chk_per_thread_in_use_list_and_count(JavaThread *jt,
3182                                                               outputStream * out,
3183                                                               int *error_cnt_p) {
3184   int chk_om_in_use_count = 0;
3185   ObjectMonitor* cur = NULL;
3186   if ((cur = get_list_head_locked(&jt->om_in_use_list)) != NULL) {
3187     // Marked the per-thread in-use list head so process the list.
3188     while (true) {
3189       chk_in_use_entry(jt, cur, out, error_cnt_p);
3190       chk_om_in_use_count++;
3191 
3192       cur = lock_next_for_traversal(cur);
3193       if (cur == NULL) {
3194         break;
3195       }
3196     }
3197   }
3198   int l_om_in_use_count = Atomic::load(&jt->om_in_use_count);
3199   if (l_om_in_use_count == chk_om_in_use_count) {
3200     out->print_cr("jt=" INTPTR_FORMAT ": om_in_use_count=%d equals "
3201                   "chk_om_in_use_count=%d", p2i(jt), l_om_in_use_count,
3202                   chk_om_in_use_count);
3203   } else {
3204     out->print_cr("ERROR: jt=" INTPTR_FORMAT ": om_in_use_count=%d is not "
3205                   "equal to chk_om_in_use_count=%d", p2i(jt), l_om_in_use_count,
3206                   chk_om_in_use_count);
3207     *error_cnt_p = *error_cnt_p + 1;
3208   }
3209 }
3210 
3211 // Log details about ObjectMonitors on the in-use lists. The 'BHL'
3212 // flags indicate why the entry is in-use, 'object' and 'object type'
3213 // indicate the associated object and its type.
3214 void ObjectSynchronizer::log_in_use_monitor_details(outputStream * out) {
3215   stringStream ss;
3216   if (Atomic::load(&om_list_globals._in_use_count) > 0) {
3217     out->print_cr("In-use global monitor info:");
3218     out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
3219     out->print_cr("%18s  %s  %18s  %18s",
3220                   "monitor", "BHL", "object", "object type");
3221     out->print_cr("==================  ===  ==================  ==================");
3222     ObjectMonitor* cur = NULL;
3223     if ((cur = get_list_head_locked(&om_list_globals._in_use_list)) != NULL) {
3224       // Marked the global in-use list head so process the list.
3225       while (true) {
3226         const oop obj = (oop) cur->object();
3227         const markWord mark = cur->header();
3228         ResourceMark rm;
3229         out->print(INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT "  %s", p2i(cur),
3230                    cur->is_busy() != 0, mark.hash() != 0, cur->owner() != NULL,
3231                    p2i(obj), obj->klass()->external_name());
3232         if (cur->is_busy() != 0) {
3233           out->print(" (%s)", cur->is_busy_to_string(&ss));
3234           ss.reset();
3235         }
3236         out->cr();
3237 
3238         cur = lock_next_for_traversal(cur);
3239         if (cur == NULL) {
3240           break;
3241         }
3242       }
3243     }
3244   }
3245 
3246   out->print_cr("In-use per-thread monitor info:");
3247   out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
3248   out->print_cr("%18s  %18s  %s  %18s  %18s",
3249                 "jt", "monitor", "BHL", "object", "object type");
3250   out->print_cr("==================  ==================  ===  ==================  ==================");
3251   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
3252     ObjectMonitor* cur = NULL;
3253     if ((cur = get_list_head_locked(&jt->om_in_use_list)) != NULL) {
3254       // Marked the global in-use list head so process the list.
3255       while (true) {
3256         const oop obj = (oop) cur->object();
3257         const markWord mark = cur->header();
3258         ResourceMark rm;
3259         out->print(INTPTR_FORMAT "  " INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT
3260                    "  %s", p2i(jt), p2i(cur), cur->is_busy() != 0,
3261                    mark.hash() != 0, cur->owner() != NULL, p2i(obj),
3262                    obj->klass()->external_name());
3263         if (cur->is_busy() != 0) {
3264           out->print(" (%s)", cur->is_busy_to_string(&ss));
3265           ss.reset();
3266         }
3267         out->cr();
3268 
3269         cur = lock_next_for_traversal(cur);
3270         if (cur == NULL) {
3271           break;
3272         }
3273       }
3274     }
3275   }
3276 
3277   out->flush();
3278 }
3279 
3280 // Log counts for the global and per-thread monitor lists and return
3281 // the population count.
3282 int ObjectSynchronizer::log_monitor_list_counts(outputStream * out) {
3283   int pop_count = 0;
3284   out->print_cr("%18s  %10s  %10s  %10s  %10s",
3285                 "Global Lists:", "InUse", "Free", "Wait", "Total");
3286   out->print_cr("==================  ==========  ==========  ==========  ==========");
3287   int l_in_use_count = Atomic::load(&om_list_globals._in_use_count);
3288   int l_free_count = Atomic::load(&om_list_globals._free_count);
3289   int l_wait_count = Atomic::load(&om_list_globals._wait_count);
3290   out->print_cr("%18s  %10d  %10d  %10d  %10d", "", l_in_use_count,
3291                 l_free_count, l_wait_count,
3292                 Atomic::load(&om_list_globals._population));
3293   pop_count += l_in_use_count + l_free_count + l_wait_count;
3294 
3295   out->print_cr("%18s  %10s  %10s  %10s",
3296                 "Per-Thread Lists:", "InUse", "Free", "Provision");
3297   out->print_cr("==================  ==========  ==========  ==========");
3298 
3299   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
3300     int l_om_in_use_count = Atomic::load(&jt->om_in_use_count);
3301     int l_om_free_count = Atomic::load(&jt->om_free_count);
3302     out->print_cr(INTPTR_FORMAT "  %10d  %10d  %10d", p2i(jt),
3303                   l_om_in_use_count, l_om_free_count, jt->om_free_provision);
3304     pop_count += l_om_in_use_count + l_om_free_count;
3305   }
3306   return pop_count;
3307 }
3308 
3309 #ifndef PRODUCT
3310 
3311 // Check if monitor belongs to the monitor cache
3312 // The list is grow-only so it's *relatively* safe to traverse
3313 // the list of extant blocks without taking a lock.
3314 
3315 int ObjectSynchronizer::verify_objmon_isinpool(ObjectMonitor *monitor) {
3316   PaddedObjectMonitor* block = Atomic::load(&g_block_list);
3317   while (block != NULL) {
3318     assert(block->object() == CHAINMARKER, "must be a block header");
3319     if (monitor > &block[0] && monitor < &block[_BLOCKSIZE]) {
3320       address mon = (address)monitor;
3321       address blk = (address)block;
3322       size_t diff = mon - blk;
3323       assert((diff % sizeof(PaddedObjectMonitor)) == 0, "must be aligned");
3324       return 1;
3325     }
3326     // unmarked_next() is not needed with g_block_list (no locking
3327     // used with block linkage _next_om fields).
3328     block = (PaddedObjectMonitor*)block->next_om();
3329   }
3330   return 0;
3331 }
3332 
3333 #endif