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