1 /*
   2  * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/vmSymbols.hpp"
  27 #include "jfr/jfrEvents.hpp"
  28 #include "gc/shared/suspendibleThreadSet.hpp"
  29 #include "logging/log.hpp"
  30 #include "logging/logStream.hpp"
  31 #include "memory/allocation.inline.hpp"
  32 #include "memory/padded.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "memory/universe.hpp"
  35 #include "oops/markWord.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "runtime/atomic.hpp"
  38 #include "runtime/biasedLocking.hpp"
  39 #include "runtime/handles.inline.hpp"
  40 #include "runtime/handshake.hpp"
  41 #include "runtime/interfaceSupport.inline.hpp"
  42 #include "runtime/lockStack.inline.hpp"
  43 #include "runtime/mutexLocker.hpp"
  44 #include "runtime/objectMonitor.hpp"
  45 #include "runtime/objectMonitor.inline.hpp"
  46 #include "runtime/os.inline.hpp"
  47 #include "runtime/osThread.hpp"
  48 #include "runtime/perfData.hpp"
  49 #include "runtime/safepointMechanism.inline.hpp"
  50 #include "runtime/safepointVerifiers.hpp"
  51 #include "runtime/sharedRuntime.hpp"
  52 #include "runtime/stubRoutines.hpp"
  53 #include "runtime/synchronizer.hpp"
  54 #include "runtime/thread.inline.hpp"
  55 #include "runtime/timer.hpp"
  56 #include "runtime/vframe.hpp"
  57 #include "runtime/vmThread.hpp"
  58 #include "utilities/align.hpp"
  59 #include "utilities/dtrace.hpp"
  60 #include "utilities/events.hpp"
  61 #include "utilities/preserveException.hpp"
  62 
  63 void MonitorList::add(ObjectMonitor* m) {
  64   ObjectMonitor* head;
  65   do {
  66     head = Atomic::load(&_head);
  67     m->set_next_om(head);
  68   } while (Atomic::cmpxchg(&_head, head, m) != head);
  69 
  70   size_t count = Atomic::add(&_count, 1u);
  71   if (count > max()) {
  72     Atomic::inc(&_max);
  73   }
  74 }
  75 
  76 size_t MonitorList::count() const {
  77   return Atomic::load(&_count);
  78 }
  79 
  80 size_t MonitorList::max() const {
  81   return Atomic::load(&_max);
  82 }
  83 
  84 // Walk the in-use list and unlink (at most MonitorDeflationMax) deflated
  85 // ObjectMonitors. Returns the number of unlinked ObjectMonitors.
  86 size_t MonitorList::unlink_deflated(Thread* current, LogStream* ls,
  87                                     elapsedTimer* timer_p,
  88                                     GrowableArray<ObjectMonitor*>* unlinked_list) {
  89   size_t unlinked_count = 0;
  90   ObjectMonitor* prev = NULL;
  91   ObjectMonitor* head = Atomic::load_acquire(&_head);
  92   ObjectMonitor* m = head;
  93   // The in-use list head can be NULL during the final audit.
  94   while (m != NULL) {
  95     if (m->is_being_async_deflated()) {
  96       // Find next live ObjectMonitor.
  97       ObjectMonitor* next = m;
  98       do {
  99         ObjectMonitor* next_next = next->next_om();
 100         unlinked_count++;
 101         unlinked_list->append(next);
 102         next = next_next;
 103         if (unlinked_count >= (size_t)MonitorDeflationMax) {
 104           // Reached the max so bail out on the gathering loop.
 105           break;
 106         }
 107       } while (next != NULL && next->is_being_async_deflated());
 108       if (prev == NULL) {
 109         ObjectMonitor* prev_head = Atomic::cmpxchg(&_head, head, next);
 110         if (prev_head != head) {
 111           // Find new prev ObjectMonitor that just got inserted.
 112           for (ObjectMonitor* n = prev_head; n != m; n = n->next_om()) {
 113             prev = n;
 114           }
 115           prev->set_next_om(next);
 116         }
 117       } else {
 118         prev->set_next_om(next);
 119       }
 120       if (unlinked_count >= (size_t)MonitorDeflationMax) {
 121         // Reached the max so bail out on the searching loop.
 122         break;
 123       }
 124       m = next;
 125     } else {
 126       prev = m;
 127       m = m->next_om();
 128     }
 129 
 130     if (current->is_Java_thread()) {
 131       // A JavaThread must check for a safepoint/handshake and honor it.
 132       ObjectSynchronizer::chk_for_block_req(current->as_Java_thread(), "unlinking",
 133                                             "unlinked_count", unlinked_count,
 134                                             ls, timer_p);
 135     }
 136   }
 137   Atomic::sub(&_count, unlinked_count);
 138   return unlinked_count;
 139 }
 140 
 141 MonitorList::Iterator MonitorList::iterator() const {
 142   return Iterator(Atomic::load_acquire(&_head));
 143 }
 144 
 145 ObjectMonitor* MonitorList::Iterator::next() {
 146   ObjectMonitor* current = _current;
 147   _current = current->next_om();
 148   return current;
 149 }
 150 
 151 // The "core" versions of monitor enter and exit reside in this file.
 152 // The interpreter and compilers contain specialized transliterated
 153 // variants of the enter-exit fast-path operations.  See c2_MacroAssembler_x86.cpp
 154 // fast_lock(...) for instance.  If you make changes here, make sure to modify the
 155 // interpreter, and both C1 and C2 fast-path inline locking code emission.
 156 //
 157 // -----------------------------------------------------------------------------
 158 
 159 #ifdef DTRACE_ENABLED
 160 
 161 // Only bother with this argument setup if dtrace is available
 162 // TODO-FIXME: probes should not fire when caller is _blocked.  assert() accordingly.
 163 
 164 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread)                           \
 165   char* bytes = NULL;                                                      \
 166   int len = 0;                                                             \
 167   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
 168   Symbol* klassname = obj->klass()->name();                                \
 169   if (klassname != NULL) {                                                 \
 170     bytes = (char*)klassname->bytes();                                     \
 171     len = klassname->utf8_length();                                        \
 172   }
 173 
 174 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis)            \
 175   {                                                                        \
 176     if (DTraceMonitorProbes) {                                             \
 177       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 178       HOTSPOT_MONITOR_WAIT(jtid,                                           \
 179                            (uintptr_t)(monitor), bytes, len, (millis));    \
 180     }                                                                      \
 181   }
 182 
 183 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY
 184 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL
 185 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED
 186 
 187 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread)                  \
 188   {                                                                        \
 189     if (DTraceMonitorProbes) {                                             \
 190       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 191       HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */             \
 192                                     (uintptr_t)(monitor), bytes, len);     \
 193     }                                                                      \
 194   }
 195 
 196 #else //  ndef DTRACE_ENABLED
 197 
 198 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon)    {;}
 199 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon)          {;}
 200 
 201 #endif // ndef DTRACE_ENABLED
 202 
 203 // This exists only as a workaround of dtrace bug 6254741
 204 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
 205   DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
 206   return 0;
 207 }
 208 
 209 static const int NINFLATIONLOCKS = 256;
 210 static os::PlatformMutex* gInflationLocks[NINFLATIONLOCKS];
 211 
 212 void ObjectSynchronizer::initialize() {
 213   for (int i = 0; i < NINFLATIONLOCKS; i++) {
 214     gInflationLocks[i] = new os::PlatformMutex();
 215   }
 216   // Start the ceiling with the estimate for one thread.
 217   set_in_use_list_ceiling(AvgMonitorsPerThreadEstimate);
 218 }
 219 
 220 MonitorList ObjectSynchronizer::_in_use_list;
 221 // monitors_used_above_threshold() policy is as follows:
 222 //
 223 // The ratio of the current _in_use_list count to the ceiling is used
 224 // to determine if we are above MonitorUsedDeflationThreshold and need
 225 // to do an async monitor deflation cycle. The ceiling is increased by
 226 // AvgMonitorsPerThreadEstimate when a thread is added to the system
 227 // and is decreased by AvgMonitorsPerThreadEstimate when a thread is
 228 // removed from the system.
 229 //
 230 // Note: If the _in_use_list max exceeds the ceiling, then
 231 // monitors_used_above_threshold() will use the in_use_list max instead
 232 // of the thread count derived ceiling because we have used more
 233 // ObjectMonitors than the estimated average.
 234 //
 235 // Note: If deflate_idle_monitors() has NoAsyncDeflationProgressMax
 236 // no-progress async monitor deflation cycles in a row, then the ceiling
 237 // is adjusted upwards by monitors_used_above_threshold().
 238 //
 239 // Start the ceiling with the estimate for one thread in initialize()
 240 // which is called after cmd line options are processed.
 241 static size_t _in_use_list_ceiling = 0;
 242 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false;
 243 bool volatile ObjectSynchronizer::_is_final_audit = false;
 244 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0;
 245 static uintx _no_progress_cnt = 0;
 246 
 247 // =====================> Quick functions
 248 
 249 // The quick_* forms are special fast-path variants used to improve
 250 // performance.  In the simplest case, a "quick_*" implementation could
 251 // simply return false, in which case the caller will perform the necessary
 252 // state transitions and call the slow-path form.
 253 // The fast-path is designed to handle frequently arising cases in an efficient
 254 // manner and is just a degenerate "optimistic" variant of the slow-path.
 255 // returns true  -- to indicate the call was satisfied.
 256 // returns false -- to indicate the call needs the services of the slow-path.
 257 // A no-loitering ordinance is in effect for code in the quick_* family
 258 // operators: safepoints or indefinite blocking (blocking that might span a
 259 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon
 260 // entry.
 261 //
 262 // Consider: An interesting optimization is to have the JIT recognize the
 263 // following common idiom:
 264 //   synchronized (someobj) { .... ; notify(); }
 265 // That is, we find a notify() or notifyAll() call that immediately precedes
 266 // the monitorexit operation.  In that case the JIT could fuse the operations
 267 // into a single notifyAndExit() runtime primitive.
 268 
 269 bool ObjectSynchronizer::quick_notify(oopDesc* obj, JavaThread* current, bool all) {
 270   assert(current->thread_state() == _thread_in_Java, "invariant");
 271   NoSafepointVerifier nsv;
 272   if (obj == NULL) return false;  // slow-path for invalid obj
 273   const markWord mark = obj->mark();
 274 
 275   if ((mark.is_fast_locked() && current->lock_stack().contains(oop(obj))) ||
 276       (mark.has_locker() && current->is_lock_owned((address)mark.locker()))) {
 277     // Degenerate notify
 278     // stack-locked by caller so by definition the implied waitset is empty.
 279     return true;
 280   }
 281 
 282   if (mark.has_monitor()) {
 283     ObjectMonitor* const mon = mark.monitor();
 284     assert(mon->object() == oop(obj), "invariant");
 285     if (mon->owner() != current) return false;  // slow-path for IMS exception
 286 
 287     if (mon->first_waiter() != NULL) {
 288       // We have one or more waiters. Since this is an inflated monitor
 289       // that we own, we can transfer one or more threads from the waitset
 290       // to the entrylist here and now, avoiding the slow-path.
 291       if (all) {
 292         DTRACE_MONITOR_PROBE(notifyAll, mon, obj, current);
 293       } else {
 294         DTRACE_MONITOR_PROBE(notify, mon, obj, current);
 295       }
 296       int free_count = 0;
 297       do {
 298         mon->INotify(current);
 299         ++free_count;
 300       } while (mon->first_waiter() != NULL && all);
 301       OM_PERFDATA_OP(Notifications, inc(free_count));
 302     }
 303     return true;
 304   }
 305 
 306   // biased locking and any other IMS exception states take the slow-path
 307   return false;
 308 }
 309 
 310 
 311 // The LockNode emitted directly at the synchronization site would have
 312 // been too big if it were to have included support for the cases of inflated
 313 // recursive enter and exit, so they go here instead.
 314 // Note that we can't safely call AsyncPrintJavaStack() from within
 315 // quick_enter() as our thread state remains _in_Java.
 316 
 317 bool ObjectSynchronizer::quick_enter(oop obj, JavaThread* current,
 318                                      BasicLock * lock) {
 319   assert(current->thread_state() == _thread_in_Java, "invariant");
 320   NoSafepointVerifier nsv;
 321   if (obj == NULL) return false;       // Need to throw NPE
 322 
 323   if (obj->klass()->is_value_based()) {
 324     return false;
 325   }
 326 
 327   const markWord mark = obj->mark();
 328 
 329   if (mark.has_monitor()) {
 330     ObjectMonitor* const m = mark.monitor();
 331     // An async deflation or GC can race us before we manage to make
 332     // the ObjectMonitor busy by setting the owner below. If we detect
 333     // that race we just bail out to the slow-path here.
 334     if (m->object_peek() == NULL) {
 335       return false;
 336     }
 337     JavaThread* const owner = (JavaThread*) m->owner_raw();
 338 
 339     // Lock contention and Transactional Lock Elision (TLE) diagnostics
 340     // and observability
 341     // Case: light contention possibly amenable to TLE
 342     // Case: TLE inimical operations such as nested/recursive synchronization
 343 
 344     if (owner == current) {
 345       m->_recursions++;
 346       return true;
 347     }
 348 
 349     // This Java Monitor is inflated so obj's header will never be
 350     // displaced to this thread's BasicLock. Make the displaced header
 351     // non-NULL so this BasicLock is not seen as recursive nor as
 352     // being locked. We do this unconditionally so that this thread's
 353     // BasicLock cannot be mis-interpreted by any stack walkers. For
 354     // performance reasons, stack walkers generally first check for
 355     // Biased Locking in the object's header, the second check is for
 356     // stack-locking in the object's header, the third check is for
 357     // recursive stack-locking in the displaced header in the BasicLock,
 358     // and last are the inflated Java Monitor (ObjectMonitor) checks.
 359     if (!UseFastLocking) {
 360       lock->set_displaced_header(markWord::unused_mark());
 361     }
 362 
 363     if (owner == NULL && m->try_set_owner_from(NULL, current) == NULL) {
 364       assert(m->_recursions == 0, "invariant");
 365       return true;
 366     }
 367   }
 368 
 369   // Note that we could inflate in quick_enter.
 370   // This is likely a useful optimization
 371   // Critically, in quick_enter() we must not:
 372   // -- perform bias revocation, or
 373   // -- block indefinitely, or
 374   // -- reach a safepoint
 375 
 376   return false;        // revert to slow-path
 377 }
 378 
 379 // Handle notifications when synchronizing on value based classes
 380 void ObjectSynchronizer::handle_sync_on_value_based_class(Handle obj, JavaThread* current) {
 381   frame last_frame = current->last_frame();
 382   bool bcp_was_adjusted = false;
 383   // Don't decrement bcp if it points to the frame's first instruction.  This happens when
 384   // handle_sync_on_value_based_class() is called because of a synchronized method.  There
 385   // is no actual monitorenter instruction in the byte code in this case.
 386   if (last_frame.is_interpreted_frame() &&
 387       (last_frame.interpreter_frame_method()->code_base() < last_frame.interpreter_frame_bcp())) {
 388     // adjust bcp to point back to monitorenter so that we print the correct line numbers
 389     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() - 1);
 390     bcp_was_adjusted = true;
 391   }
 392 
 393   if (DiagnoseSyncOnValueBasedClasses == FATAL_EXIT) {
 394     ResourceMark rm(current);
 395     stringStream ss;
 396     current->print_stack_on(&ss);
 397     char* base = (char*)strstr(ss.base(), "at");
 398     char* newline = (char*)strchr(ss.base(), '\n');
 399     if (newline != NULL) {
 400       *newline = '\0';
 401     }
 402     fatal("Synchronizing on object " INTPTR_FORMAT " of klass %s %s", p2i(obj()), obj->klass()->external_name(), base);
 403   } else {
 404     assert(DiagnoseSyncOnValueBasedClasses == LOG_WARNING, "invalid value for DiagnoseSyncOnValueBasedClasses");
 405     ResourceMark rm(current);
 406     Log(valuebasedclasses) vblog;
 407 
 408     vblog.info("Synchronizing on object " INTPTR_FORMAT " of klass %s", p2i(obj()), obj->klass()->external_name());
 409     if (current->has_last_Java_frame()) {
 410       LogStream info_stream(vblog.info());
 411       current->print_stack_on(&info_stream);
 412     } else {
 413       vblog.info("Cannot find the last Java frame");
 414     }
 415 
 416     EventSyncOnValueBasedClass event;
 417     if (event.should_commit()) {
 418       event.set_valueBasedClass(obj->klass());
 419       event.commit();
 420     }
 421   }
 422 
 423   if (bcp_was_adjusted) {
 424     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() + 1);
 425   }
 426 }
 427 
 428 // -----------------------------------------------------------------------------
 429 // Monitor Enter/Exit
 430 // The interpreter and compiler assembly code tries to lock using the fast path
 431 // of this algorithm. Make sure to update that code if the following function is
 432 // changed. The implementation is extremely sensitive to race condition. Be careful.
 433 
 434 void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) {
 435   if (obj->klass()->is_value_based()) {
 436     handle_sync_on_value_based_class(obj, current);
 437   }
 438 
 439   if (UseFastLocking) {
 440     LockStack& lock_stack = current->lock_stack();
 441 
 442     markWord header = obj()->mark_acquire();
 443     while (true) {
 444       if (header.is_neutral()) {
 445         assert(!lock_stack.contains(obj()), "thread must not already hold the lock");
 446         // Try to swing into 'fast-locked' state without inflating.
 447         markWord locked_header = header.set_fast_locked();
 448         markWord witness = obj()->cas_set_mark(locked_header, header);
 449         if (witness == header) {
 450           // Successfully fast-locked, push object to lock-stack and return.
 451           lock_stack.push(obj());
 452           return;
 453         }
 454         // Otherwise retry.
 455         header = witness;
 456       } else {
 457         // Fall-through to inflate-enter.
 458         break;
 459       }
 460     }
 461   } else {
 462     if (UseBiasedLocking) {
 463       BiasedLocking::revoke(current, obj);
 464     }
 465 
 466     markWord mark = obj->mark();
 467     if (mark.is_neutral()) {
 468       // Anticipate successful CAS -- the ST of the displaced mark must
 469       // be visible <= the ST performed by the CAS.
 470       lock->set_displaced_header(mark);
 471       if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) {
 472         return;
 473       }
 474       // Fall through to inflate() ...
 475     } else if (mark.has_locker() &&
 476                current->is_lock_owned((address) mark.locker())) {
 477       assert(lock != mark.locker(), "must not re-lock the same lock");
 478       assert(lock != (BasicLock*) obj->mark().value(), "don't relock with same BasicLock");
 479       lock->set_displaced_header(markWord::from_pointer(NULL));
 480       return;
 481     }
 482 
 483     // The object header will never be displaced to this lock,
 484     // so it does not matter what the value is, except that it
 485     // must be non-zero to avoid looking like a re-entrant lock,
 486     // and must not look locked either.
 487     lock->set_displaced_header(markWord::unused_mark());
 488   }
 489 
 490   // An async deflation can race after the inflate() call and before
 491   // enter() can make the ObjectMonitor busy. enter() returns false if
 492   // we have lost the race to async deflation and we simply try again.
 493   while (true) {
 494     ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_monitor_enter);
 495     if (monitor->enter(current)) {
 496       return;
 497     }
 498   }
 499 }
 500 
 501 void ObjectSynchronizer::exit(oop object, BasicLock* lock, JavaThread* current) {
 502   markWord mark = object->mark();
 503     if (UseFastLocking) {
 504       if (mark.is_fast_locked()) {
 505         markWord unlocked_header = mark.set_unlocked();
 506         markWord witness = object->cas_set_mark(unlocked_header, mark);
 507         if (witness != mark) {
 508           // Another thread beat us, it can only have installed an anonymously locked monitor at this point.
 509           // Fetch that monitor, set owner correctly to this thread, and exit it (allowing waiting threads to enter).
 510           assert(witness.has_monitor(), "must have monitor");
 511           ObjectMonitor* monitor = witness.monitor();
 512           assert(monitor->is_owner_anonymous(), "must be anonymous owner");
 513           monitor->set_owner_from_anonymous(current);
 514           monitor->exit(current);
 515       }
 516       LockStack& lock_stack = current->lock_stack();
 517       lock_stack.remove(object);
 518       return;
 519     }
 520   } else {
 521     markWord dhw = lock->displaced_header();
 522     if (dhw.value() == 0) {
 523       // If the displaced header is NULL, then this exit matches up with
 524       // a recursive enter. No real work to do here except for diagnostics.
 525 #ifndef PRODUCT
 526       if (mark != markWord::INFLATING()) {
 527         // Only do diagnostics if we are not racing an inflation. Simply
 528         // exiting a recursive enter of a Java Monitor that is being
 529         // inflated is safe; see the has_monitor() comment below.
 530         assert(!mark.is_neutral(), "invariant");
 531         assert(!mark.has_locker() ||
 532                current->is_lock_owned((address)mark.locker()), "invariant");
 533         if (mark.has_monitor()) {
 534           // The BasicLock's displaced_header is marked as a recursive
 535           // enter and we have an inflated Java Monitor (ObjectMonitor).
 536           // This is a special case where the Java Monitor was inflated
 537           // after this thread entered the stack-lock recursively. When a
 538           // Java Monitor is inflated, we cannot safely walk the Java
 539           // Monitor owner's stack and update the BasicLocks because a
 540           // Java Monitor can be asynchronously inflated by a thread that
 541           // does not own the Java Monitor.
 542           ObjectMonitor* m = mark.monitor();
 543           assert(m->object()->mark() == mark, "invariant");
 544           assert(m->is_entered(current), "invariant");
 545         }
 546       }
 547 #endif
 548       return;
 549     }
 550 
 551     if (mark == markWord::from_pointer(lock)) {
 552       // If the object is stack-locked by the current thread, try to
 553       // swing the displaced header from the BasicLock back to the mark.
 554       assert(dhw.is_neutral(), "invariant");
 555       if (object->cas_set_mark(dhw, mark) == mark) {
 556         return;
 557       }
 558     }
 559   }
 560 
 561   // We have to take the slow-path of possible inflation and then exit.
 562   // The ObjectMonitor* can't be async deflated until ownership is
 563   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 564   ObjectMonitor* monitor = inflate(current, object, inflate_cause_vm_internal);
 565   if (UseFastLocking && monitor->is_owner_anonymous()) {
 566     // It must be us. Pop lock object from lock stack.
 567     LockStack& lock_stack = current->lock_stack();
 568     oop popped = lock_stack.pop();
 569     assert(popped == object, "must be owned by this thread");
 570     monitor->set_owner_from_anonymous(current);
 571   }
 572   monitor->exit(current);
 573 }
 574 
 575 // -----------------------------------------------------------------------------
 576 // Class Loader  support to workaround deadlocks on the class loader lock objects
 577 // Also used by GC
 578 // complete_exit()/reenter() are used to wait on a nested lock
 579 // i.e. to give up an outer lock completely and then re-enter
 580 // Used when holding nested locks - lock acquisition order: lock1 then lock2
 581 //  1) complete_exit lock1 - saving recursion count
 582 //  2) wait on lock2
 583 //  3) when notified on lock2, unlock lock2
 584 //  4) reenter lock1 with original recursion count
 585 //  5) lock lock2
 586 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 587 intx ObjectSynchronizer::complete_exit(Handle obj, JavaThread* current) {
 588   if (UseBiasedLocking) {
 589     BiasedLocking::revoke(current, obj);
 590     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 591   }
 592 
 593   // The ObjectMonitor* can't be async deflated until ownership is
 594   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 595   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_vm_internal);
 596   intptr_t ret_code = monitor->complete_exit(current);
 597   return ret_code;
 598 }
 599 
 600 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 601 void ObjectSynchronizer::reenter(Handle obj, intx recursions, JavaThread* current) {
 602   if (UseBiasedLocking) {
 603     BiasedLocking::revoke(current, obj);
 604     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 605   }
 606 
 607   // An async deflation can race after the inflate() call and before
 608   // reenter() -> enter() can make the ObjectMonitor busy. reenter() ->
 609   // enter() returns false if we have lost the race to async deflation
 610   // and we simply try again.
 611   while (true) {
 612     ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_vm_internal);
 613     if (monitor->reenter(recursions, current)) {
 614       return;
 615     }
 616   }
 617 }
 618 
 619 // -----------------------------------------------------------------------------
 620 // JNI locks on java objects
 621 // NOTE: must use heavy weight monitor to handle jni monitor enter
 622 void ObjectSynchronizer::jni_enter(Handle obj, JavaThread* current) {
 623   if (obj->klass()->is_value_based()) {
 624     handle_sync_on_value_based_class(obj, current);
 625   }
 626 
 627   // the current locking is from JNI instead of Java code
 628   if (UseBiasedLocking) {
 629     BiasedLocking::revoke(current, obj);
 630     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 631   }
 632   current->set_current_pending_monitor_is_from_java(false);
 633   // An async deflation can race after the inflate() call and before
 634   // enter() can make the ObjectMonitor busy. enter() returns false if
 635   // we have lost the race to async deflation and we simply try again.
 636   while (true) {
 637     ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_jni_enter);
 638     if (monitor->enter(current)) {
 639       break;
 640     }
 641   }
 642   current->set_current_pending_monitor_is_from_java(true);
 643 }
 644 
 645 // NOTE: must use heavy weight monitor to handle jni monitor exit
 646 void ObjectSynchronizer::jni_exit(oop obj, TRAPS) {
 647   JavaThread* current = THREAD;
 648   if (UseBiasedLocking) {
 649     Handle h_obj(current, obj);
 650     BiasedLocking::revoke(current, h_obj);
 651     obj = h_obj();
 652   }
 653   assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 654 
 655   // The ObjectMonitor* can't be async deflated until ownership is
 656   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 657   ObjectMonitor* monitor = inflate(current, obj, inflate_cause_jni_exit);
 658   // If this thread has locked the object, exit the monitor. We
 659   // intentionally do not use CHECK on check_owner because we must exit the
 660   // monitor even if an exception was already pending.
 661   if (monitor->check_owner(THREAD)) {
 662     monitor->exit(current);
 663   }
 664 }
 665 
 666 // -----------------------------------------------------------------------------
 667 // Internal VM locks on java objects
 668 // standard constructor, allows locking failures
 669 ObjectLocker::ObjectLocker(Handle obj, JavaThread* thread) {
 670   _thread = thread;
 671   _thread->check_for_valid_safepoint_state();
 672   _obj = obj;
 673 
 674   if (_obj() != NULL) {
 675     ObjectSynchronizer::enter(_obj, &_lock, _thread);
 676   }
 677 }
 678 
 679 ObjectLocker::~ObjectLocker() {
 680   if (_obj() != NULL) {
 681     ObjectSynchronizer::exit(_obj(), &_lock, _thread);
 682   }
 683 }
 684 
 685 
 686 // -----------------------------------------------------------------------------
 687 //  Wait/Notify/NotifyAll
 688 // NOTE: must use heavy weight monitor to handle wait()
 689 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 690   JavaThread* current = THREAD;
 691   if (UseBiasedLocking) {
 692     BiasedLocking::revoke(current, obj);
 693     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 694   }
 695   if (millis < 0) {
 696     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 697   }
 698   // The ObjectMonitor* can't be async deflated because the _waiters
 699   // field is incremented before ownership is dropped and decremented
 700   // after ownership is regained.
 701   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_wait);
 702 
 703   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), current, millis);
 704   monitor->wait(millis, true, THREAD); // Not CHECK as we need following code
 705 
 706   // This dummy call is in place to get around dtrace bug 6254741.  Once
 707   // that's fixed we can uncomment the following line, remove the call
 708   // and change this function back into a "void" func.
 709   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 710   int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
 711   return ret_code;
 712 }
 713 
 714 // No exception are possible in this case as we only use this internally when locking is
 715 // correct and we have to wait until notified - so no interrupts or timeouts.
 716 void ObjectSynchronizer::wait_uninterruptibly(Handle obj, JavaThread* current) {
 717   if (UseBiasedLocking) {
 718     BiasedLocking::revoke(current, obj);
 719     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 720   }
 721   // The ObjectMonitor* can't be async deflated because the _waiters
 722   // field is incremented before ownership is dropped and decremented
 723   // after ownership is regained.
 724   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_wait);
 725   monitor->wait(0 /* wait-forever */, false /* not interruptible */, current);
 726 }
 727 
 728 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 729   JavaThread* current = THREAD;
 730   if (UseBiasedLocking) {
 731     BiasedLocking::revoke(current, obj);
 732     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 733   }
 734 
 735   markWord mark = obj->mark();
 736   if ((mark.is_fast_locked() && current->lock_stack().contains(obj())) ||
 737       (mark.has_locker() && current->is_lock_owned((address)mark.locker()))) {
 738     // Not inflated so there can't be any waiters to notify.
 739     return;
 740   }
 741   // The ObjectMonitor* can't be async deflated until ownership is
 742   // dropped by the calling thread.
 743   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_notify);
 744   monitor->notify(CHECK);
 745 }
 746 
 747 // NOTE: see comment of notify()
 748 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 749   JavaThread* current = THREAD;
 750   if (UseBiasedLocking) {
 751     BiasedLocking::revoke(current, obj);
 752     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 753   }
 754 
 755   markWord mark = obj->mark();
 756   if ((mark.is_fast_locked() && current->lock_stack().contains(obj())) ||
 757       (mark.has_locker() && current->is_lock_owned((address)mark.locker()))) {
 758     // Not inflated so there can't be any waiters to notify.
 759     return;
 760   }
 761   // The ObjectMonitor* can't be async deflated until ownership is
 762   // dropped by the calling thread.
 763   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_notify);
 764   monitor->notifyAll(CHECK);
 765 }
 766 
 767 // -----------------------------------------------------------------------------
 768 // Hash Code handling
 769 
 770 struct SharedGlobals {
 771   char         _pad_prefix[OM_CACHE_LINE_SIZE];
 772   // This is a highly shared mostly-read variable.
 773   // To avoid false-sharing it needs to be the sole occupant of a cache line.
 774   volatile int stw_random;
 775   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 776   // Hot RW variable -- Sequester to avoid false-sharing
 777   volatile int hc_sequence;
 778   DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 779 };
 780 
 781 static SharedGlobals GVars;
 782 
 783 static markWord read_stable_mark(oop obj) {
 784   markWord mark = obj->mark();
 785   if (!mark.is_being_inflated() || UseFastLocking) {
 786     return mark;       // normal fast-path return
 787   }
 788 
 789   int its = 0;
 790   for (;;) {
 791     markWord mark = obj->mark();
 792     if (!mark.is_being_inflated()) {
 793       return mark;    // normal fast-path return
 794     }
 795 
 796     // The object is being inflated by some other thread.
 797     // The caller of read_stable_mark() must wait for inflation to complete.
 798     // Avoid live-lock.
 799 
 800     ++its;
 801     if (its > 10000 || !os::is_MP()) {
 802       if (its & 1) {
 803         os::naked_yield();
 804       } else {
 805         // Note that the following code attenuates the livelock problem but is not
 806         // a complete remedy.  A more complete solution would require that the inflating
 807         // thread hold the associated inflation lock.  The following code simply restricts
 808         // the number of spinners to at most one.  We'll have N-2 threads blocked
 809         // on the inflationlock, 1 thread holding the inflation lock and using
 810         // a yield/park strategy, and 1 thread in the midst of inflation.
 811         // A more refined approach would be to change the encoding of INFLATING
 812         // to allow encapsulation of a native thread pointer.  Threads waiting for
 813         // inflation to complete would use CAS to push themselves onto a singly linked
 814         // list rooted at the markword.  Once enqueued, they'd loop, checking a per-thread flag
 815         // and calling park().  When inflation was complete the thread that accomplished inflation
 816         // would detach the list and set the markword to inflated with a single CAS and
 817         // then for each thread on the list, set the flag and unpark() the thread.
 818 
 819         // Index into the lock array based on the current object address.
 820         static_assert(is_power_of_2(NINFLATIONLOCKS), "must be");
 821         int ix = (cast_from_oop<intptr_t>(obj) >> 5) & (NINFLATIONLOCKS-1);
 822         int YieldThenBlock = 0;
 823         assert(ix >= 0 && ix < NINFLATIONLOCKS, "invariant");
 824         gInflationLocks[ix]->lock();
 825         while (obj->mark() == markWord::INFLATING()) {
 826           // Beware: naked_yield() is advisory and has almost no effect on some platforms
 827           // so we periodically call current->_ParkEvent->park(1).
 828           // We use a mixed spin/yield/block mechanism.
 829           if ((YieldThenBlock++) >= 16) {
 830             Thread::current()->_ParkEvent->park(1);
 831           } else {
 832             os::naked_yield();
 833           }
 834         }
 835         gInflationLocks[ix]->unlock();
 836       }
 837     } else {
 838       SpinPause();       // SMP-polite spinning
 839     }
 840   }
 841 }
 842 
 843 // hashCode() generation :
 844 //
 845 // Possibilities:
 846 // * MD5Digest of {obj,stw_random}
 847 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function.
 848 // * A DES- or AES-style SBox[] mechanism
 849 // * One of the Phi-based schemes, such as:
 850 //   2654435761 = 2^32 * Phi (golden ratio)
 851 //   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ;
 852 // * A variation of Marsaglia's shift-xor RNG scheme.
 853 // * (obj ^ stw_random) is appealing, but can result
 854 //   in undesirable regularity in the hashCode values of adjacent objects
 855 //   (objects allocated back-to-back, in particular).  This could potentially
 856 //   result in hashtable collisions and reduced hashtable efficiency.
 857 //   There are simple ways to "diffuse" the middle address bits over the
 858 //   generated hashCode values:
 859 
 860 static inline intptr_t get_next_hash(Thread* current, oop obj) {
 861   intptr_t value = 0;
 862   if (hashCode == 0) {
 863     // This form uses global Park-Miller RNG.
 864     // On MP system we'll have lots of RW access to a global, so the
 865     // mechanism induces lots of coherency traffic.
 866     value = os::random();
 867   } else if (hashCode == 1) {
 868     // This variation has the property of being stable (idempotent)
 869     // between STW operations.  This can be useful in some of the 1-0
 870     // synchronization schemes.
 871     intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3;
 872     value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random;
 873   } else if (hashCode == 2) {
 874     value = 1;            // for sensitivity testing
 875   } else if (hashCode == 3) {
 876     value = ++GVars.hc_sequence;
 877   } else if (hashCode == 4) {
 878     value = cast_from_oop<intptr_t>(obj);
 879   } else {
 880     // Marsaglia's xor-shift scheme with thread-specific state
 881     // This is probably the best overall implementation -- we'll
 882     // likely make this the default in future releases.
 883     unsigned t = current->_hashStateX;
 884     t ^= (t << 11);
 885     current->_hashStateX = current->_hashStateY;
 886     current->_hashStateY = current->_hashStateZ;
 887     current->_hashStateZ = current->_hashStateW;
 888     unsigned v = current->_hashStateW;
 889     v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
 890     current->_hashStateW = v;
 891     value = v;
 892   }
 893 
 894   value &= markWord::hash_mask;
 895   if (value == 0) value = 0xBAD;
 896   assert(value != markWord::no_hash, "invariant");
 897   return value;
 898 }
 899 
 900 static bool is_lock_owned(Thread* thread, oop obj) {
 901   assert(UseFastLocking, "only call this with fast-locking enabled");
 902   return thread->is_Java_thread() ? reinterpret_cast<JavaThread*>(thread)->lock_stack().contains(obj) : false;
 903 }
 904 
 905 intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) {
 906   if (UseBiasedLocking) {
 907     // NOTE: many places throughout the JVM do not expect a safepoint
 908     // to be taken here. However, we only ever bias Java instances and all
 909     // of the call sites of identity_hash that might revoke biases have
 910     // been checked to make sure they can handle a safepoint. The
 911     // added check of the bias pattern is to avoid useless calls to
 912     // thread-local storage.
 913     if (obj->mark().has_bias_pattern()) {
 914       // Handle for oop obj in case of STW safepoint
 915       Handle hobj(current, obj);
 916       if (SafepointSynchronize::is_at_safepoint()) {
 917         BiasedLocking::revoke_at_safepoint(hobj);
 918       } else {
 919         BiasedLocking::revoke(current->as_Java_thread(), hobj);
 920       }
 921       obj = hobj();
 922       assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 923     }
 924   }
 925 
 926   while (true) {
 927     ObjectMonitor* monitor = NULL;
 928     markWord temp, test;
 929     intptr_t hash;
 930     markWord mark = read_stable_mark(obj);
 931 
 932     // object should remain ineligible for biased locking
 933     assert(!mark.has_bias_pattern(), "invariant");
 934 
 935     if (mark.is_neutral()) {               // if this is a normal header
 936       hash = mark.hash();
 937       if (hash != 0) {                     // if it has a hash, just return it
 938         return hash;
 939       }
 940       hash = get_next_hash(current, obj);  // get a new hash
 941       temp = mark.copy_set_hash(hash);     // merge the hash into header
 942                                            // try to install the hash
 943       test = obj->cas_set_mark(temp, mark);
 944       if (test == mark) {                  // if the hash was installed, return it
 945         return hash;
 946       }
 947       // Failed to install the hash. It could be that another thread
 948       // installed the hash just before our attempt or inflation has
 949       // occurred or... so we fall thru to inflate the monitor for
 950       // stability and then install the hash.
 951     } else if (mark.has_monitor()) {
 952       monitor = mark.monitor();
 953       temp = monitor->header();
 954       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
 955       hash = temp.hash();
 956       if (hash != 0) {
 957         // It has a hash.
 958 
 959         // Separate load of dmw/header above from the loads in
 960         // is_being_async_deflated().
 961 
 962         // dmw/header and _contentions may get written by different threads.
 963         // Make sure to observe them in the same order when having several observers.
 964         OrderAccess::loadload_for_IRIW();
 965 
 966         if (monitor->is_being_async_deflated()) {
 967           // But we can't safely use the hash if we detect that async
 968           // deflation has occurred. So we attempt to restore the
 969           // header/dmw to the object's header so that we only retry
 970           // once if the deflater thread happens to be slow.
 971           monitor->install_displaced_markword_in_object(obj);
 972           continue;
 973         }
 974         return hash;
 975       }
 976       // Fall thru so we only have one place that installs the hash in
 977       // the ObjectMonitor.
 978     } else if (mark.is_fast_locked() && is_lock_owned(current, obj)) {
 979       // This is a fast lock owned by the calling thread so use the
 980       // markWord from the object.
 981       hash = mark.hash();
 982       if (hash != 0) {                  // if it has a hash, just return it
 983         return hash;
 984       }
 985     } else if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
 986       // This is a stack lock owned by the calling thread so fetch the
 987       // displaced markWord from the BasicLock on the stack.
 988       temp = mark.displaced_mark_helper();
 989       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
 990       hash = temp.hash();
 991       if (hash != 0) {                  // if it has a hash, just return it
 992         return hash;
 993       }
 994       // WARNING:
 995       // The displaced header in the BasicLock on a thread's stack
 996       // is strictly immutable. It CANNOT be changed in ANY cases.
 997       // So we have to inflate the stack lock into an ObjectMonitor
 998       // even if the current thread owns the lock. The BasicLock on
 999       // a thread's stack can be asynchronously read by other threads
1000       // during an inflate() call so any change to that stack memory
1001       // may not propagate to other threads correctly.
1002     }
1003 
1004     // Inflate the monitor to set the hash.
1005 
1006     // An async deflation can race after the inflate() call and before we
1007     // can update the ObjectMonitor's header with the hash value below.
1008     monitor = inflate(current, obj, inflate_cause_hash_code);
1009     // Load ObjectMonitor's header/dmw field and see if it has a hash.
1010     mark = monitor->header();
1011     assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
1012     hash = mark.hash();
1013     if (hash == 0) {                       // if it does not have a hash
1014       hash = get_next_hash(current, obj);  // get a new hash
1015       temp = mark.copy_set_hash(hash)   ;  // merge the hash into header
1016       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
1017       uintptr_t v = Atomic::cmpxchg((volatile uintptr_t*)monitor->header_addr(), mark.value(), temp.value());
1018       test = markWord(v);
1019       if (test != mark) {
1020         // The attempt to update the ObjectMonitor's header/dmw field
1021         // did not work. This can happen if another thread managed to
1022         // merge in the hash just before our cmpxchg().
1023         // If we add any new usages of the header/dmw field, this code
1024         // will need to be updated.
1025         hash = test.hash();
1026         assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value());
1027         assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash");
1028       }
1029       if (monitor->is_being_async_deflated()) {
1030         // If we detect that async deflation has occurred, then we
1031         // attempt to restore the header/dmw to the object's header
1032         // so that we only retry once if the deflater thread happens
1033         // to be slow.
1034         monitor->install_displaced_markword_in_object(obj);
1035         continue;
1036       }
1037     }
1038     // We finally get the hash.
1039     return hash;
1040   }
1041 }
1042 
1043 // Deprecated -- use FastHashCode() instead.
1044 
1045 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
1046   return FastHashCode(Thread::current(), obj());
1047 }
1048 
1049 
1050 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* current,
1051                                                    Handle h_obj) {
1052   if (UseBiasedLocking) {
1053     BiasedLocking::revoke(current, h_obj);
1054     assert(!h_obj->mark().has_bias_pattern(), "biases should be revoked by now");
1055   }
1056 
1057   assert(current == JavaThread::current(), "Can only be called on current thread");
1058   oop obj = h_obj();
1059 
1060   markWord mark = read_stable_mark(obj);
1061 
1062   // Uncontended case, header points to stack
1063   if (mark.has_locker()) {
1064     return current->is_lock_owned((address)mark.locker());
1065   }
1066 
1067   // Fast-locking case.
1068   if (mark.is_fast_locked()) {
1069     return current->lock_stack().contains(h_obj());
1070   }
1071 
1072   // Contended case, header points to ObjectMonitor (tagged pointer)
1073   if (mark.has_monitor()) {
1074     // The first stage of async deflation does not affect any field
1075     // used by this comparison so the ObjectMonitor* is usable here.
1076     ObjectMonitor* monitor = mark.monitor();
1077     return monitor->is_entered(current) != 0;
1078   }
1079   // Unlocked case, header in place
1080   assert(mark.is_neutral(), "sanity check");
1081   return false;
1082 }
1083 
1084 // FIXME: jvmti should call this
1085 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
1086   if (UseBiasedLocking) {
1087     if (SafepointSynchronize::is_at_safepoint()) {
1088       BiasedLocking::revoke_at_safepoint(h_obj);
1089     } else {
1090       BiasedLocking::revoke(JavaThread::current(), h_obj);
1091     }
1092     assert(!h_obj->mark().has_bias_pattern(), "biases should be revoked by now");
1093   }
1094 
1095   oop obj = h_obj();
1096   markWord mark = read_stable_mark(obj);
1097 
1098   // Uncontended case, header points to stack
1099   if (mark.has_locker()) {
1100     return Threads::owning_thread_from_monitor_owner(t_list, (address) mark.locker());
1101   }
1102 
1103   if (mark.is_fast_locked()) {
1104     return Threads::owning_thread_from_object(t_list, h_obj());
1105   }
1106 
1107   // Contended case, header points to ObjectMonitor (tagged pointer)
1108   if (mark.has_monitor()) {
1109     // The first stage of async deflation does not affect any field
1110     // used by this comparison so the ObjectMonitor* is usable here.
1111     ObjectMonitor* monitor = mark.monitor();
1112     assert(monitor != NULL, "monitor should be non-null");
1113     return Threads::owning_thread_from_monitor(t_list, monitor);
1114   }
1115 
1116   return NULL;
1117 }
1118 
1119 // Visitors ...
1120 
1121 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure, JavaThread* thread) {
1122   MonitorList::Iterator iter = _in_use_list.iterator();
1123   while (iter.has_next()) {
1124     ObjectMonitor* mid = iter.next();
1125     if (mid->owner() != thread) {
1126       continue;
1127     }
1128     if (!mid->is_being_async_deflated() && mid->object_peek() != NULL) {
1129       // Only process with closure if the object is set.
1130 
1131       // monitors_iterate() is only called at a safepoint or when the
1132       // target thread is suspended or when the target thread is
1133       // operating on itself. The current closures in use today are
1134       // only interested in an owned ObjectMonitor and ownership
1135       // cannot be dropped under the calling contexts so the
1136       // ObjectMonitor cannot be async deflated.
1137       closure->do_monitor(mid);
1138     }
1139   }
1140 }
1141 
1142 static bool monitors_used_above_threshold(MonitorList* list) {
1143   if (MonitorUsedDeflationThreshold == 0) {  // disabled case is easy
1144     return false;
1145   }
1146   // Start with ceiling based on a per-thread estimate:
1147   size_t ceiling = ObjectSynchronizer::in_use_list_ceiling();
1148   size_t old_ceiling = ceiling;
1149   if (ceiling < list->max()) {
1150     // The max used by the system has exceeded the ceiling so use that:
1151     ceiling = list->max();
1152   }
1153   size_t monitors_used = list->count();
1154   if (monitors_used == 0) {  // empty list is easy
1155     return false;
1156   }
1157   if (NoAsyncDeflationProgressMax != 0 &&
1158       _no_progress_cnt >= NoAsyncDeflationProgressMax) {
1159     float remainder = (100.0 - MonitorUsedDeflationThreshold) / 100.0;
1160     size_t new_ceiling = ceiling + (ceiling * remainder) + 1;
1161     ObjectSynchronizer::set_in_use_list_ceiling(new_ceiling);
1162     log_info(monitorinflation)("Too many deflations without progress; "
1163                                "bumping in_use_list_ceiling from " SIZE_FORMAT
1164                                " to " SIZE_FORMAT, old_ceiling, new_ceiling);
1165     _no_progress_cnt = 0;
1166     ceiling = new_ceiling;
1167   }
1168 
1169   // Check if our monitor usage is above the threshold:
1170   size_t monitor_usage = (monitors_used * 100LL) / ceiling;
1171   return int(monitor_usage) > MonitorUsedDeflationThreshold;
1172 }
1173 
1174 size_t ObjectSynchronizer::in_use_list_ceiling() {
1175   return _in_use_list_ceiling;
1176 }
1177 
1178 void ObjectSynchronizer::dec_in_use_list_ceiling() {
1179   Atomic::sub(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
1180 }
1181 
1182 void ObjectSynchronizer::inc_in_use_list_ceiling() {
1183   Atomic::add(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
1184 }
1185 
1186 void ObjectSynchronizer::set_in_use_list_ceiling(size_t new_value) {
1187   _in_use_list_ceiling = new_value;
1188 }
1189 
1190 bool ObjectSynchronizer::is_async_deflation_needed() {
1191   if (is_async_deflation_requested()) {
1192     // Async deflation request.
1193     return true;
1194   }
1195   if (AsyncDeflationInterval > 0 &&
1196       time_since_last_async_deflation_ms() > AsyncDeflationInterval &&
1197       monitors_used_above_threshold(&_in_use_list)) {
1198     // It's been longer than our specified deflate interval and there
1199     // are too many monitors in use. We don't deflate more frequently
1200     // than AsyncDeflationInterval (unless is_async_deflation_requested)
1201     // in order to not swamp the MonitorDeflationThread.
1202     return true;
1203   }
1204   return false;
1205 }
1206 
1207 bool ObjectSynchronizer::request_deflate_idle_monitors() {
1208   JavaThread* current = JavaThread::current();
1209   bool ret_code = false;
1210 
1211   jlong last_time = last_async_deflation_time_ns();
1212   set_is_async_deflation_requested(true);
1213   {
1214     MonitorLocker ml(MonitorDeflation_lock, Mutex::_no_safepoint_check_flag);
1215     ml.notify_all();
1216   }
1217   const int N_CHECKS = 5;
1218   for (int i = 0; i < N_CHECKS; i++) {  // sleep for at most 5 seconds
1219     if (last_async_deflation_time_ns() > last_time) {
1220       log_info(monitorinflation)("Async Deflation happened after %d check(s).", i);
1221       ret_code = true;
1222       break;
1223     }
1224     {
1225       // JavaThread has to honor the blocking protocol.
1226       ThreadBlockInVM tbivm(current);
1227       os::naked_short_sleep(999);  // sleep for almost 1 second
1228     }
1229   }
1230   if (!ret_code) {
1231     log_info(monitorinflation)("Async Deflation DID NOT happen after %d checks.", N_CHECKS);
1232   }
1233 
1234   return ret_code;
1235 }
1236 
1237 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() {
1238   return (os::javaTimeNanos() - last_async_deflation_time_ns()) / (NANOUNITS / MILLIUNITS);
1239 }
1240 
1241 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1242                                        const oop obj,
1243                                        ObjectSynchronizer::InflateCause cause) {
1244   assert(event != NULL, "invariant");
1245   assert(event->should_commit(), "invariant");
1246   event->set_monitorClass(obj->klass());
1247   event->set_address((uintptr_t)(void*)obj);
1248   event->set_cause((u1)cause);
1249   event->commit();
1250 }
1251 
1252 // Fast path code shared by multiple functions
1253 void ObjectSynchronizer::inflate_helper(oop obj) {
1254   markWord mark = obj->mark();
1255   if (mark.has_monitor()) {
1256     ObjectMonitor* monitor = mark.monitor();
1257     markWord dmw = monitor->header();
1258     assert(dmw.is_neutral(), "sanity check: header=" INTPTR_FORMAT, dmw.value());
1259     return;
1260   }
1261   (void)inflate(Thread::current(), obj, inflate_cause_vm_internal);
1262 }
1263 
1264 ObjectMonitor* ObjectSynchronizer::inflate(Thread* current, oop object,
1265                                            const InflateCause cause) {
1266   EventJavaMonitorInflate event;
1267 
1268   for (;;) {
1269     const markWord mark = object->mark();
1270     assert(!mark.has_bias_pattern(), "invariant");
1271 
1272     // The mark can be in one of the following states:
1273     // *  Inflated     - just return
1274     // *  Stack-locked - coerce it to inflated
1275     // *  INFLATING    - busy wait for conversion to complete
1276     // *  Neutral      - aggressively inflate the object.
1277     // *  BIASED       - Illegal.  We should never see this
1278 
1279     // CASE: inflated
1280     if (mark.has_monitor()) {
1281       ObjectMonitor* inf = mark.monitor();
1282       markWord dmw = inf->header();
1283       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
1284       if (UseFastLocking && inf->is_owner_anonymous() && is_lock_owned(current, object)) {
1285         inf->set_owner_from_anonymous(current);
1286         assert(current->is_Java_thread(), "must be Java thread");
1287         reinterpret_cast<JavaThread*>(current)->lock_stack().remove(object);
1288       }
1289       return inf;
1290     }
1291 
1292     // CASE: inflation in progress - inflating over a stack-lock.
1293     // Some other thread is converting from stack-locked to inflated.
1294     // Only that thread can complete inflation -- other threads must wait.
1295     // The INFLATING value is transient.
1296     // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
1297     // We could always eliminate polling by parking the thread on some auxiliary list.
1298     // NOTE: We need to check UseFastLocking here, because with fast-locking, the header
1299     // may legitimately be zero: cleared lock-bits and all upper header bits zero.
1300     // With fast-locking, the INFLATING protocol is not used.
1301     if (mark == markWord::INFLATING() && !UseFastLocking) {
1302       read_stable_mark(object);
1303       continue;
1304     }
1305 
1306     // CASE: stack-locked
1307     // Could be stack-locked either by this thread or by some other thread.
1308     //
1309     // Note that we allocate the ObjectMonitor speculatively, _before_ attempting
1310     // to install INFLATING into the mark word.  We originally installed INFLATING,
1311     // allocated the ObjectMonitor, and then finally STed the address of the
1312     // ObjectMonitor into the mark.  This was correct, but artificially lengthened
1313     // the interval in which INFLATING appeared in the mark, thus increasing
1314     // the odds of inflation contention.
1315 
1316     LogStreamHandle(Trace, monitorinflation) lsh;
1317     if (mark.is_fast_locked()) {
1318       assert(UseFastLocking, "can only happen with fast-locking");
1319       ObjectMonitor* monitor = new ObjectMonitor(object);
1320       monitor->set_header(mark.set_unlocked());
1321       bool own = is_lock_owned(current, object);
1322       if (own) {
1323         // Owned by us.
1324         monitor->set_owner_from(NULL, current);
1325       } else {
1326         // Owned by somebody else.
1327         monitor->set_owner_anonymous();
1328       }
1329       markWord monitor_mark = markWord::encode(monitor);
1330       markWord witness = object->cas_set_mark(monitor_mark, mark);
1331       if (witness == mark) {
1332         // Success! Return inflated monitor.
1333         if (own) {
1334           assert(current->is_Java_thread(), "must be: checked in is_lock_owned()");
1335           reinterpret_cast<JavaThread*>(current)->lock_stack().remove(object);
1336         }
1337         // Once the ObjectMonitor is configured and object is associated
1338         // with the ObjectMonitor, it is safe to allow async deflation:
1339         _in_use_list.add(monitor);
1340 
1341         // Hopefully the performance counters are allocated on distinct
1342         // cache lines to avoid false sharing on MP systems ...
1343         OM_PERFDATA_OP(Inflations, inc());
1344         if (log_is_enabled(Trace, monitorinflation)) {
1345           ResourceMark rm(current);
1346           lsh.print_cr("inflate(locked): object=" INTPTR_FORMAT ", mark="
1347                        INTPTR_FORMAT ", type='%s'", p2i(object),
1348                        object->mark().value(), object->klass()->external_name());
1349         }
1350         if (event.should_commit()) {
1351           post_monitor_inflate_event(&event, object, cause);
1352         }
1353         return monitor;
1354       } else {
1355         delete monitor;
1356         continue;
1357       }
1358     }
1359 
1360     if (mark.has_locker()) {
1361       assert(!UseFastLocking, "can not happen with fast-locking");
1362       ObjectMonitor* m = new ObjectMonitor(object);
1363       // Optimistically prepare the ObjectMonitor - anticipate successful CAS
1364       // We do this before the CAS in order to minimize the length of time
1365       // in which INFLATING appears in the mark.
1366 
1367       markWord cmp = object->cas_set_mark(markWord::INFLATING(), mark);
1368       if (cmp != mark) {
1369         delete m;
1370         continue;       // Interference -- just retry
1371       }
1372 
1373       // We've successfully installed INFLATING (0) into the mark-word.
1374       // This is the only case where 0 will appear in a mark-word.
1375       // Only the singular thread that successfully swings the mark-word
1376       // to 0 can perform (or more precisely, complete) inflation.
1377       //
1378       // Why do we CAS a 0 into the mark-word instead of just CASing the
1379       // mark-word from the stack-locked value directly to the new inflated state?
1380       // Consider what happens when a thread unlocks a stack-locked object.
1381       // It attempts to use CAS to swing the displaced header value from the
1382       // on-stack BasicLock back into the object header.  Recall also that the
1383       // header value (hash code, etc) can reside in (a) the object header, or
1384       // (b) a displaced header associated with the stack-lock, or (c) a displaced
1385       // header in an ObjectMonitor.  The inflate() routine must copy the header
1386       // value from the BasicLock on the owner's stack to the ObjectMonitor, all
1387       // the while preserving the hashCode stability invariants.  If the owner
1388       // decides to release the lock while the value is 0, the unlock will fail
1389       // and control will eventually pass from slow_exit() to inflate.  The owner
1390       // will then spin, waiting for the 0 value to disappear.   Put another way,
1391       // the 0 causes the owner to stall if the owner happens to try to
1392       // drop the lock (restoring the header from the BasicLock to the object)
1393       // while inflation is in-progress.  This protocol avoids races that might
1394       // would otherwise permit hashCode values to change or "flicker" for an object.
1395       // Critically, while object->mark is 0 mark.displaced_mark_helper() is stable.
1396       // 0 serves as a "BUSY" inflate-in-progress indicator.
1397 
1398 
1399       // fetch the displaced mark from the owner's stack.
1400       // The owner can't die or unwind past the lock while our INFLATING
1401       // object is in the mark.  Furthermore the owner can't complete
1402       // an unlock on the object, either.
1403       markWord dmw = mark.displaced_mark_helper();
1404       // Catch if the object's header is not neutral (not locked and
1405       // not marked is what we care about here).
1406       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
1407 
1408       // Setup monitor fields to proper values -- prepare the monitor
1409       m->set_header(dmw);
1410 
1411       // Optimization: if the mark.locker stack address is associated
1412       // with this thread we could simply set m->_owner = current.
1413       // Note that a thread can inflate an object
1414       // that it has stack-locked -- as might happen in wait() -- directly
1415       // with CAS.  That is, we can avoid the xchg-NULL .... ST idiom.
1416       m->set_owner_from(NULL, mark.locker());
1417       // TODO-FIXME: assert BasicLock->dhw != 0.
1418 
1419       // Must preserve store ordering. The monitor state must
1420       // be stable at the time of publishing the monitor address.
1421       guarantee(object->mark() == markWord::INFLATING(), "invariant");
1422       // Release semantics so that above set_object() is seen first.
1423       object->release_set_mark(markWord::encode(m));
1424 
1425       // Once ObjectMonitor is configured and the object is associated
1426       // with the ObjectMonitor, it is safe to allow async deflation:
1427       _in_use_list.add(m);
1428 
1429       // Hopefully the performance counters are allocated on distinct cache lines
1430       // to avoid false sharing on MP systems ...
1431       OM_PERFDATA_OP(Inflations, inc());
1432       if (log_is_enabled(Trace, monitorinflation)) {
1433         ResourceMark rm(current);
1434         lsh.print_cr("inflate(locked): object=" INTPTR_FORMAT ", mark="
1435                      INTPTR_FORMAT ", type='%s'", p2i(object),
1436                      object->mark().value(), object->klass()->external_name());
1437       }
1438       if (event.should_commit()) {
1439         post_monitor_inflate_event(&event, object, cause);
1440       }
1441       return m;
1442     }
1443 
1444     // CASE: neutral
1445     // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1446     // If we know we're inflating for entry it's better to inflate by swinging a
1447     // pre-locked ObjectMonitor pointer into the object header.   A successful
1448     // CAS inflates the object *and* confers ownership to the inflating thread.
1449     // In the current implementation we use a 2-step mechanism where we CAS()
1450     // to inflate and then CAS() again to try to swing _owner from NULL to current.
1451     // An inflateTry() method that we could call from enter() would be useful.
1452 
1453     // Catch if the object's header is not neutral (not locked and
1454     // not marked is what we care about here).
1455     assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
1456     ObjectMonitor* m = new ObjectMonitor(object);
1457     // prepare m for installation - set monitor to initial state
1458     m->set_header(mark);
1459 
1460     if (object->cas_set_mark(markWord::encode(m), mark) != mark) {
1461       delete m;
1462       m = NULL;
1463       continue;
1464       // interference - the markword changed - just retry.
1465       // The state-transitions are one-way, so there's no chance of
1466       // live-lock -- "Inflated" is an absorbing state.
1467     }
1468 
1469     // Once the ObjectMonitor is configured and object is associated
1470     // with the ObjectMonitor, it is safe to allow async deflation:
1471     _in_use_list.add(m);
1472 
1473     // Hopefully the performance counters are allocated on distinct
1474     // cache lines to avoid false sharing on MP systems ...
1475     OM_PERFDATA_OP(Inflations, inc());
1476     if (log_is_enabled(Trace, monitorinflation)) {
1477       ResourceMark rm(current);
1478       lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark="
1479                    INTPTR_FORMAT ", type='%s'", p2i(object),
1480                    object->mark().value(), object->klass()->external_name());
1481     }
1482     if (event.should_commit()) {
1483       post_monitor_inflate_event(&event, object, cause);
1484     }
1485     return m;
1486   }
1487 }
1488 
1489 void ObjectSynchronizer::chk_for_block_req(JavaThread* current, const char* op_name,
1490                                            const char* cnt_name, size_t cnt,
1491                                            LogStream* ls, elapsedTimer* timer_p) {
1492   if (!SafepointMechanism::should_process(current)) {
1493     return;
1494   }
1495 
1496   // A safepoint/handshake has started.
1497   if (ls != NULL) {
1498     timer_p->stop();
1499     ls->print_cr("pausing %s: %s=" SIZE_FORMAT ", in_use_list stats: ceiling="
1500                  SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1501                  op_name, cnt_name, cnt, in_use_list_ceiling(),
1502                  _in_use_list.count(), _in_use_list.max());
1503   }
1504 
1505   {
1506     // Honor block request.
1507     ThreadBlockInVM tbivm(current);
1508   }
1509 
1510   if (ls != NULL) {
1511     ls->print_cr("resuming %s: in_use_list stats: ceiling=" SIZE_FORMAT
1512                  ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT, op_name,
1513                  in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max());
1514     timer_p->start();
1515   }
1516 }
1517 
1518 // Walk the in-use list and deflate (at most MonitorDeflationMax) idle
1519 // ObjectMonitors. Returns the number of deflated ObjectMonitors.
1520 size_t ObjectSynchronizer::deflate_monitor_list(Thread* current, LogStream* ls,
1521                                                 elapsedTimer* timer_p) {
1522   MonitorList::Iterator iter = _in_use_list.iterator();
1523   size_t deflated_count = 0;
1524 
1525   while (iter.has_next()) {
1526     if (deflated_count >= (size_t)MonitorDeflationMax) {
1527       break;
1528     }
1529     ObjectMonitor* mid = iter.next();
1530     if (mid->deflate_monitor()) {
1531       deflated_count++;
1532     }
1533 
1534     if (current->is_Java_thread()) {
1535       // A JavaThread must check for a safepoint/handshake and honor it.
1536       chk_for_block_req(current->as_Java_thread(), "deflation", "deflated_count",
1537                         deflated_count, ls, timer_p);
1538     }
1539   }
1540 
1541   return deflated_count;
1542 }
1543 
1544 class HandshakeForDeflation : public HandshakeClosure {
1545  public:
1546   HandshakeForDeflation() : HandshakeClosure("HandshakeForDeflation") {}
1547 
1548   void do_thread(Thread* thread) {
1549     log_trace(monitorinflation)("HandshakeForDeflation::do_thread: thread="
1550                                 INTPTR_FORMAT, p2i(thread));
1551   }
1552 };
1553 
1554 class VM_RendezvousGCThreads : public VM_Operation {
1555 public:
1556   bool evaluate_at_safepoint() const override { return false; }
1557   VMOp_Type type() const override { return VMOp_RendezvousGCThreads; }
1558   void doit() override {
1559     SuspendibleThreadSet::synchronize();
1560     SuspendibleThreadSet::desynchronize();
1561   };
1562 };
1563 
1564 // This function is called by the MonitorDeflationThread to deflate
1565 // ObjectMonitors. It is also called via do_final_audit_and_print_stats()
1566 // by the VMThread.
1567 size_t ObjectSynchronizer::deflate_idle_monitors() {
1568   Thread* current = Thread::current();
1569   if (current->is_Java_thread()) {
1570     // The async deflation request has been processed.
1571     _last_async_deflation_time_ns = os::javaTimeNanos();
1572     set_is_async_deflation_requested(false);
1573   }
1574 
1575   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1576   LogStreamHandle(Info, monitorinflation) lsh_info;
1577   LogStream* ls = NULL;
1578   if (log_is_enabled(Debug, monitorinflation)) {
1579     ls = &lsh_debug;
1580   } else if (log_is_enabled(Info, monitorinflation)) {
1581     ls = &lsh_info;
1582   }
1583 
1584   elapsedTimer timer;
1585   if (ls != NULL) {
1586     ls->print_cr("begin deflating: in_use_list stats: ceiling=" SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1587                  in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max());
1588     timer.start();
1589   }
1590 
1591   // Deflate some idle ObjectMonitors.
1592   size_t deflated_count = deflate_monitor_list(current, ls, &timer);
1593   if (deflated_count > 0 || is_final_audit()) {
1594     // There are ObjectMonitors that have been deflated or this is the
1595     // final audit and all the remaining ObjectMonitors have been
1596     // deflated, BUT the MonitorDeflationThread blocked for the final
1597     // safepoint during unlinking.
1598 
1599     // Unlink deflated ObjectMonitors from the in-use list.
1600     ResourceMark rm;
1601     GrowableArray<ObjectMonitor*> delete_list((int)deflated_count);
1602     size_t unlinked_count = _in_use_list.unlink_deflated(current, ls, &timer,
1603                                                          &delete_list);
1604     if (current->is_Java_thread()) {
1605       if (ls != NULL) {
1606         timer.stop();
1607         ls->print_cr("before handshaking: unlinked_count=" SIZE_FORMAT
1608                      ", in_use_list stats: ceiling=" SIZE_FORMAT ", count="
1609                      SIZE_FORMAT ", max=" SIZE_FORMAT,
1610                      unlinked_count, in_use_list_ceiling(),
1611                      _in_use_list.count(), _in_use_list.max());
1612       }
1613 
1614       // A JavaThread needs to handshake in order to safely free the
1615       // ObjectMonitors that were deflated in this cycle.
1616       // Also, we sync and desync GC threads around the handshake, so that they can
1617       // safely read the mark-word and look-through to the object-monitor, without
1618       // being afraid that the object-monitor is going away.
1619       HandshakeForDeflation hfd_hc;
1620       Handshake::execute(&hfd_hc);
1621       VM_RendezvousGCThreads sync_gc;
1622       VMThread::execute(&sync_gc);
1623 
1624       if (ls != NULL) {
1625         ls->print_cr("after handshaking: in_use_list stats: ceiling="
1626                      SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1627                      in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max());
1628         timer.start();
1629       }
1630     }
1631 
1632     // After the handshake, safely free the ObjectMonitors that were
1633     // deflated in this cycle.
1634     size_t deleted_count = 0;
1635     for (ObjectMonitor* monitor: delete_list) {
1636       delete monitor;
1637       deleted_count++;
1638 
1639       if (current->is_Java_thread()) {
1640         // A JavaThread must check for a safepoint/handshake and honor it.
1641         chk_for_block_req(current->as_Java_thread(), "deletion", "deleted_count",
1642                           deleted_count, ls, &timer);
1643       }
1644     }
1645   }
1646 
1647   if (ls != NULL) {
1648     timer.stop();
1649     if (deflated_count != 0 || log_is_enabled(Debug, monitorinflation)) {
1650       ls->print_cr("deflated " SIZE_FORMAT " monitors in %3.7f secs",
1651                    deflated_count, timer.seconds());
1652     }
1653     ls->print_cr("end deflating: in_use_list stats: ceiling=" SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1654                  in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max());
1655   }
1656 
1657   OM_PERFDATA_OP(MonExtant, set_value(_in_use_list.count()));
1658   OM_PERFDATA_OP(Deflations, inc(deflated_count));
1659 
1660   GVars.stw_random = os::random();
1661 
1662   if (deflated_count != 0) {
1663     _no_progress_cnt = 0;
1664   } else {
1665     _no_progress_cnt++;
1666   }
1667 
1668   return deflated_count;
1669 }
1670 
1671 // Monitor cleanup on JavaThread::exit
1672 
1673 // Iterate through monitor cache and attempt to release thread's monitors
1674 class ReleaseJavaMonitorsClosure: public MonitorClosure {
1675  private:
1676   JavaThread* _thread;
1677 
1678  public:
1679   ReleaseJavaMonitorsClosure(JavaThread* thread) : _thread(thread) {}
1680   void do_monitor(ObjectMonitor* mid) {
1681     (void)mid->complete_exit(_thread);
1682   }
1683 };
1684 
1685 // Release all inflated monitors owned by current thread.  Lightweight monitors are
1686 // ignored.  This is meant to be called during JNI thread detach which assumes
1687 // all remaining monitors are heavyweight.  All exceptions are swallowed.
1688 // Scanning the extant monitor list can be time consuming.
1689 // A simple optimization is to add a per-thread flag that indicates a thread
1690 // called jni_monitorenter() during its lifetime.
1691 //
1692 // Instead of NoSafepointVerifier it might be cheaper to
1693 // use an idiom of the form:
1694 //   auto int tmp = SafepointSynchronize::_safepoint_counter ;
1695 //   <code that must not run at safepoint>
1696 //   guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
1697 // Since the tests are extremely cheap we could leave them enabled
1698 // for normal product builds.
1699 
1700 void ObjectSynchronizer::release_monitors_owned_by_thread(JavaThread* current) {
1701   assert(current == JavaThread::current(), "must be current Java thread");
1702   NoSafepointVerifier nsv;
1703   ReleaseJavaMonitorsClosure rjmc(current);
1704   ObjectSynchronizer::monitors_iterate(&rjmc, current);
1705   assert(!current->has_pending_exception(), "Should not be possible");
1706   current->clear_pending_exception();
1707 }
1708 
1709 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) {
1710   switch (cause) {
1711     case inflate_cause_vm_internal:    return "VM Internal";
1712     case inflate_cause_monitor_enter:  return "Monitor Enter";
1713     case inflate_cause_wait:           return "Monitor Wait";
1714     case inflate_cause_notify:         return "Monitor Notify";
1715     case inflate_cause_hash_code:      return "Monitor Hash Code";
1716     case inflate_cause_jni_enter:      return "JNI Monitor Enter";
1717     case inflate_cause_jni_exit:       return "JNI Monitor Exit";
1718     default:
1719       ShouldNotReachHere();
1720   }
1721   return "Unknown";
1722 }
1723 
1724 //------------------------------------------------------------------------------
1725 // Debugging code
1726 
1727 u_char* ObjectSynchronizer::get_gvars_addr() {
1728   return (u_char*)&GVars;
1729 }
1730 
1731 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() {
1732   return (u_char*)&GVars.hc_sequence;
1733 }
1734 
1735 size_t ObjectSynchronizer::get_gvars_size() {
1736   return sizeof(SharedGlobals);
1737 }
1738 
1739 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() {
1740   return (u_char*)&GVars.stw_random;
1741 }
1742 
1743 // Do the final audit and print of ObjectMonitor stats; must be done
1744 // by the VMThread at VM exit time.
1745 void ObjectSynchronizer::do_final_audit_and_print_stats() {
1746   assert(Thread::current()->is_VM_thread(), "sanity check");
1747 
1748   if (is_final_audit()) {  // Only do the audit once.
1749     return;
1750   }
1751   set_is_final_audit();
1752 
1753   if (log_is_enabled(Info, monitorinflation)) {
1754     // Do a deflation in order to reduce the in-use monitor population
1755     // that is reported by ObjectSynchronizer::log_in_use_monitor_details()
1756     // which is called by ObjectSynchronizer::audit_and_print_stats().
1757     while (ObjectSynchronizer::deflate_idle_monitors() != 0) {
1758       ; // empty
1759     }
1760     // The other audit_and_print_stats() call is done at the Debug
1761     // level at a safepoint in ObjectSynchronizer::do_safepoint_work().
1762     ObjectSynchronizer::audit_and_print_stats(true /* on_exit */);
1763   }
1764 }
1765 
1766 // This function can be called at a safepoint or it can be called when
1767 // we are trying to exit the VM. When we are trying to exit the VM, the
1768 // list walker functions can run in parallel with the other list
1769 // operations so spin-locking is used for safety.
1770 //
1771 // Calls to this function can be added in various places as a debugging
1772 // aid; pass 'true' for the 'on_exit' parameter to have in-use monitor
1773 // details logged at the Info level and 'false' for the 'on_exit'
1774 // parameter to have in-use monitor details logged at the Trace level.
1775 //
1776 void ObjectSynchronizer::audit_and_print_stats(bool on_exit) {
1777   assert(on_exit || SafepointSynchronize::is_at_safepoint(), "invariant");
1778 
1779   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1780   LogStreamHandle(Info, monitorinflation) lsh_info;
1781   LogStreamHandle(Trace, monitorinflation) lsh_trace;
1782   LogStream* ls = NULL;
1783   if (log_is_enabled(Trace, monitorinflation)) {
1784     ls = &lsh_trace;
1785   } else if (log_is_enabled(Debug, monitorinflation)) {
1786     ls = &lsh_debug;
1787   } else if (log_is_enabled(Info, monitorinflation)) {
1788     ls = &lsh_info;
1789   }
1790   assert(ls != NULL, "sanity check");
1791 
1792   int error_cnt = 0;
1793 
1794   ls->print_cr("Checking in_use_list:");
1795   chk_in_use_list(ls, &error_cnt);
1796 
1797   if (error_cnt == 0) {
1798     ls->print_cr("No errors found in in_use_list checks.");
1799   } else {
1800     log_error(monitorinflation)("found in_use_list errors: error_cnt=%d", error_cnt);
1801   }
1802 
1803   if ((on_exit && log_is_enabled(Info, monitorinflation)) ||
1804       (!on_exit && log_is_enabled(Trace, monitorinflation))) {
1805     // When exiting this log output is at the Info level. When called
1806     // at a safepoint, this log output is at the Trace level since
1807     // there can be a lot of it.
1808     log_in_use_monitor_details(ls);
1809   }
1810 
1811   ls->flush();
1812 
1813   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
1814 }
1815 
1816 // Check the in_use_list; log the results of the checks.
1817 void ObjectSynchronizer::chk_in_use_list(outputStream* out, int *error_cnt_p) {
1818   size_t l_in_use_count = _in_use_list.count();
1819   size_t l_in_use_max = _in_use_list.max();
1820   out->print_cr("count=" SIZE_FORMAT ", max=" SIZE_FORMAT, l_in_use_count,
1821                 l_in_use_max);
1822 
1823   size_t ck_in_use_count = 0;
1824   MonitorList::Iterator iter = _in_use_list.iterator();
1825   while (iter.has_next()) {
1826     ObjectMonitor* mid = iter.next();
1827     chk_in_use_entry(mid, out, error_cnt_p);
1828     ck_in_use_count++;
1829   }
1830 
1831   if (l_in_use_count == ck_in_use_count) {
1832     out->print_cr("in_use_count=" SIZE_FORMAT " equals ck_in_use_count="
1833                   SIZE_FORMAT, l_in_use_count, ck_in_use_count);
1834   } else {
1835     out->print_cr("WARNING: in_use_count=" SIZE_FORMAT " is not equal to "
1836                   "ck_in_use_count=" SIZE_FORMAT, l_in_use_count,
1837                   ck_in_use_count);
1838   }
1839 
1840   size_t ck_in_use_max = _in_use_list.max();
1841   if (l_in_use_max == ck_in_use_max) {
1842     out->print_cr("in_use_max=" SIZE_FORMAT " equals ck_in_use_max="
1843                   SIZE_FORMAT, l_in_use_max, ck_in_use_max);
1844   } else {
1845     out->print_cr("WARNING: in_use_max=" SIZE_FORMAT " is not equal to "
1846                   "ck_in_use_max=" SIZE_FORMAT, l_in_use_max, ck_in_use_max);
1847   }
1848 }
1849 
1850 // Check an in-use monitor entry; log any errors.
1851 void ObjectSynchronizer::chk_in_use_entry(ObjectMonitor* n, outputStream* out,
1852                                           int* error_cnt_p) {
1853   if (n->owner_is_DEFLATER_MARKER()) {
1854     // This should not happen, but if it does, it is not fatal.
1855     out->print_cr("WARNING: monitor=" INTPTR_FORMAT ": in-use monitor is "
1856                   "deflated.", p2i(n));
1857     return;
1858   }
1859   if (n->header().value() == 0) {
1860     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor must "
1861                   "have non-NULL _header field.", p2i(n));
1862     *error_cnt_p = *error_cnt_p + 1;
1863   }
1864   const oop obj = n->object_peek();
1865   if (obj != NULL) {
1866     const markWord mark = obj->mark();
1867     if (!mark.has_monitor()) {
1868       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
1869                     "object does not think it has a monitor: obj="
1870                     INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n),
1871                     p2i(obj), mark.value());
1872       *error_cnt_p = *error_cnt_p + 1;
1873     }
1874     ObjectMonitor* const obj_mon = mark.monitor();
1875     if (n != obj_mon) {
1876       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
1877                     "object does not refer to the same monitor: obj="
1878                     INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon="
1879                     INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon));
1880       *error_cnt_p = *error_cnt_p + 1;
1881     }
1882   }
1883 }
1884 
1885 // Log details about ObjectMonitors on the in_use_list. The 'BHL'
1886 // flags indicate why the entry is in-use, 'object' and 'object type'
1887 // indicate the associated object and its type.
1888 void ObjectSynchronizer::log_in_use_monitor_details(outputStream* out) {
1889   stringStream ss;
1890   if (_in_use_list.count() > 0) {
1891     out->print_cr("In-use monitor info:");
1892     out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
1893     out->print_cr("%18s  %s  %18s  %18s",
1894                   "monitor", "BHL", "object", "object type");
1895     out->print_cr("==================  ===  ==================  ==================");
1896     MonitorList::Iterator iter = _in_use_list.iterator();
1897     while (iter.has_next()) {
1898       ObjectMonitor* mid = iter.next();
1899       const oop obj = mid->object_peek();
1900       const markWord mark = mid->header();
1901       ResourceMark rm;
1902       out->print(INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT "  %s", p2i(mid),
1903                  mid->is_busy(), mark.hash() != 0, mid->owner() != NULL,
1904                  p2i(obj), obj == NULL ? "" : obj->klass()->external_name());
1905       if (mid->is_busy()) {
1906         out->print(" (%s)", mid->is_busy_to_string(&ss));
1907         ss.reset();
1908       }
1909       out->cr();
1910     }
1911   }
1912 
1913   out->flush();
1914 }