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