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