< prev index next >

src/hotspot/share/runtime/synchronizer.cpp

Print this page

   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 "logging/log.hpp"
  29 #include "logging/logStream.hpp"
  30 #include "memory/allocation.inline.hpp"
  31 #include "memory/padded.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/markWord.hpp"
  35 #include "oops/oop.inline.hpp"
  36 #include "runtime/atomic.hpp"
  37 #include "runtime/biasedLocking.hpp"
  38 #include "runtime/handles.inline.hpp"
  39 #include "runtime/handshake.hpp"
  40 #include "runtime/interfaceSupport.inline.hpp"

  41 #include "runtime/mutexLocker.hpp"
  42 #include "runtime/objectMonitor.hpp"
  43 #include "runtime/objectMonitor.inline.hpp"
  44 #include "runtime/os.inline.hpp"
  45 #include "runtime/osThread.hpp"
  46 #include "runtime/perfData.hpp"
  47 #include "runtime/safepointMechanism.inline.hpp"
  48 #include "runtime/safepointVerifiers.hpp"
  49 #include "runtime/sharedRuntime.hpp"
  50 #include "runtime/stubRoutines.hpp"
  51 #include "runtime/synchronizer.hpp"
  52 #include "runtime/thread.inline.hpp"
  53 #include "runtime/timer.hpp"
  54 #include "runtime/vframe.hpp"
  55 #include "runtime/vmThread.hpp"
  56 #include "utilities/align.hpp"
  57 #include "utilities/dtrace.hpp"
  58 #include "utilities/events.hpp"
  59 #include "utilities/preserveException.hpp"
  60 

 253 // returns true  -- to indicate the call was satisfied.
 254 // returns false -- to indicate the call needs the services of the slow-path.
 255 // A no-loitering ordinance is in effect for code in the quick_* family
 256 // operators: safepoints or indefinite blocking (blocking that might span a
 257 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon
 258 // entry.
 259 //
 260 // Consider: An interesting optimization is to have the JIT recognize the
 261 // following common idiom:
 262 //   synchronized (someobj) { .... ; notify(); }
 263 // That is, we find a notify() or notifyAll() call that immediately precedes
 264 // the monitorexit operation.  In that case the JIT could fuse the operations
 265 // into a single notifyAndExit() runtime primitive.
 266 
 267 bool ObjectSynchronizer::quick_notify(oopDesc* obj, JavaThread* current, bool all) {
 268   assert(current->thread_state() == _thread_in_Java, "invariant");
 269   NoSafepointVerifier nsv;
 270   if (obj == NULL) return false;  // slow-path for invalid obj
 271   const markWord mark = obj->mark();
 272 
 273   if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {

 274     // Degenerate notify
 275     // stack-locked by caller so by definition the implied waitset is empty.
 276     return true;
 277   }
 278 
 279   if (mark.has_monitor()) {
 280     ObjectMonitor* const mon = mark.monitor();
 281     assert(mon->object() == oop(obj), "invariant");
 282     if (mon->owner() != current) return false;  // slow-path for IMS exception
 283 
 284     if (mon->first_waiter() != NULL) {
 285       // We have one or more waiters. Since this is an inflated monitor
 286       // that we own, we can transfer one or more threads from the waitset
 287       // to the entrylist here and now, avoiding the slow-path.
 288       if (all) {
 289         DTRACE_MONITOR_PROBE(notifyAll, mon, obj, current);
 290       } else {
 291         DTRACE_MONITOR_PROBE(notify, mon, obj, current);
 292       }
 293       int free_count = 0;

 336     // Lock contention and Transactional Lock Elision (TLE) diagnostics
 337     // and observability
 338     // Case: light contention possibly amenable to TLE
 339     // Case: TLE inimical operations such as nested/recursive synchronization
 340 
 341     if (owner == current) {
 342       m->_recursions++;
 343       return true;
 344     }
 345 
 346     // This Java Monitor is inflated so obj's header will never be
 347     // displaced to this thread's BasicLock. Make the displaced header
 348     // non-NULL so this BasicLock is not seen as recursive nor as
 349     // being locked. We do this unconditionally so that this thread's
 350     // BasicLock cannot be mis-interpreted by any stack walkers. For
 351     // performance reasons, stack walkers generally first check for
 352     // Biased Locking in the object's header, the second check is for
 353     // stack-locking in the object's header, the third check is for
 354     // recursive stack-locking in the displaced header in the BasicLock,
 355     // and last are the inflated Java Monitor (ObjectMonitor) checks.
 356     lock->set_displaced_header(markWord::unused_mark());


 357 
 358     if (owner == NULL && m->try_set_owner_from(NULL, current) == NULL) {
 359       assert(m->_recursions == 0, "invariant");
 360       return true;
 361     }
 362   }
 363 
 364   // Note that we could inflate in quick_enter.
 365   // This is likely a useful optimization
 366   // Critically, in quick_enter() we must not:
 367   // -- perform bias revocation, or
 368   // -- block indefinitely, or
 369   // -- reach a safepoint
 370 
 371   return false;        // revert to slow-path
 372 }
 373 
 374 // Handle notifications when synchronizing on value based classes
 375 void ObjectSynchronizer::handle_sync_on_value_based_class(Handle obj, JavaThread* current) {
 376   frame last_frame = current->last_frame();

 414       event.commit();
 415     }
 416   }
 417 
 418   if (bcp_was_adjusted) {
 419     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() + 1);
 420   }
 421 }
 422 
 423 // -----------------------------------------------------------------------------
 424 // Monitor Enter/Exit
 425 // The interpreter and compiler assembly code tries to lock using the fast path
 426 // of this algorithm. Make sure to update that code if the following function is
 427 // changed. The implementation is extremely sensitive to race condition. Be careful.
 428 
 429 void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) {
 430   if (obj->klass()->is_value_based()) {
 431     handle_sync_on_value_based_class(obj, current);
 432   }
 433 
 434   if (UseBiasedLocking) {
 435     BiasedLocking::revoke(current, obj);
 436   }
 437 
 438   markWord mark = obj->mark();
 439   assert(!mark.has_bias_pattern(), "should not see bias pattern here");




















 440 
 441   if (mark.is_neutral()) {
 442     // Anticipate successful CAS -- the ST of the displaced mark must
 443     // be visible <= the ST performed by the CAS.
 444     lock->set_displaced_header(mark);
 445     if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) {









 446       return;
 447     }
 448     // Fall through to inflate() ...
 449   } else if (mark.has_locker() &&
 450              current->is_lock_owned((address)mark.locker())) {
 451     assert(lock != mark.locker(), "must not re-lock the same lock");
 452     assert(lock != (BasicLock*)obj->mark().value(), "don't relock with same BasicLock");
 453     lock->set_displaced_header(markWord::from_pointer(NULL));
 454     return;
 455   }
 456 
 457   // The object header will never be displaced to this lock,
 458   // so it does not matter what the value is, except that it
 459   // must be non-zero to avoid looking like a re-entrant lock,
 460   // and must not look locked either.
 461   lock->set_displaced_header(markWord::unused_mark());
 462   // An async deflation can race after the inflate() call and before
 463   // enter() can make the ObjectMonitor busy. enter() returns false if
 464   // we have lost the race to async deflation and we simply try again.
 465   while (true) {
 466     ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_monitor_enter);
 467     if (monitor->enter(current)) {
 468       return;
 469     }
 470   }
 471 }
 472 
 473 void ObjectSynchronizer::exit(oop object, BasicLock* lock, JavaThread* current) {
 474   markWord mark = object->mark();
 475   // We cannot check for Biased Locking if we are racing an inflation.
 476   assert(mark == markWord::INFLATING() ||
 477          !mark.has_bias_pattern(), "should not see bias pattern here");
 478 
 479   markWord dhw = lock->displaced_header();
 480   if (dhw.value() == 0) {
 481     // If the displaced header is NULL, then this exit matches up with
 482     // a recursive enter. No real work to do here except for diagnostics.
 483 #ifndef PRODUCT
 484     if (mark != markWord::INFLATING()) {
 485       // Only do diagnostics if we are not racing an inflation. Simply
 486       // exiting a recursive enter of a Java Monitor that is being
 487       // inflated is safe; see the has_monitor() comment below.
 488       assert(!mark.is_neutral(), "invariant");
 489       assert(!mark.has_locker() ||
 490              current->is_lock_owned((address)mark.locker()), "invariant");
 491       if (mark.has_monitor()) {
 492         // The BasicLock's displaced_header is marked as a recursive
 493         // enter and we have an inflated Java Monitor (ObjectMonitor).
 494         // This is a special case where the Java Monitor was inflated
 495         // after this thread entered the stack-lock recursively. When a
 496         // Java Monitor is inflated, we cannot safely walk the Java
 497         // Monitor owner's stack and update the BasicLocks because a
 498         // Java Monitor can be asynchronously inflated by a thread that
 499         // does not own the Java Monitor.
 500         ObjectMonitor* m = mark.monitor();
 501         assert(m->object()->mark() == mark, "invariant");
 502         assert(m->is_entered(current), "invariant");
 503       }



 504     }



























 505 #endif
 506     return;
 507   }
 508 
 509   if (mark == markWord::from_pointer(lock)) {
 510     // If the object is stack-locked by the current thread, try to
 511     // swing the displaced header from the BasicLock back to the mark.
 512     assert(dhw.is_neutral(), "invariant");
 513     if (object->cas_set_mark(dhw, mark) == mark) {
 514       return;
 515     }









 516   }
 517 
 518   // We have to take the slow-path of possible inflation and then exit.
 519   // The ObjectMonitor* can't be async deflated until ownership is
 520   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 521   ObjectMonitor* monitor = inflate(current, object, inflate_cause_vm_internal);







 522   monitor->exit(current);
 523 }
 524 
 525 // -----------------------------------------------------------------------------
 526 // Class Loader  support to workaround deadlocks on the class loader lock objects
 527 // Also used by GC
 528 // complete_exit()/reenter() are used to wait on a nested lock
 529 // i.e. to give up an outer lock completely and then re-enter
 530 // Used when holding nested locks - lock acquisition order: lock1 then lock2
 531 //  1) complete_exit lock1 - saving recursion count
 532 //  2) wait on lock2
 533 //  3) when notified on lock2, unlock lock2
 534 //  4) reenter lock1 with original recursion count
 535 //  5) lock lock2
 536 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 537 intx ObjectSynchronizer::complete_exit(Handle obj, JavaThread* current) {
 538   if (UseBiasedLocking) {
 539     BiasedLocking::revoke(current, obj);
 540     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 541   }

 666 void ObjectSynchronizer::wait_uninterruptibly(Handle obj, JavaThread* current) {
 667   if (UseBiasedLocking) {
 668     BiasedLocking::revoke(current, obj);
 669     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 670   }
 671   // The ObjectMonitor* can't be async deflated because the _waiters
 672   // field is incremented before ownership is dropped and decremented
 673   // after ownership is regained.
 674   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_wait);
 675   monitor->wait(0 /* wait-forever */, false /* not interruptible */, current);
 676 }
 677 
 678 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 679   JavaThread* current = THREAD;
 680   if (UseBiasedLocking) {
 681     BiasedLocking::revoke(current, obj);
 682     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 683   }
 684 
 685   markWord mark = obj->mark();
 686   if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {

 687     // Not inflated so there can't be any waiters to notify.
 688     return;
 689   }
 690   // The ObjectMonitor* can't be async deflated until ownership is
 691   // dropped by the calling thread.
 692   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_notify);
 693   monitor->notify(CHECK);
 694 }
 695 
 696 // NOTE: see comment of notify()
 697 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 698   JavaThread* current = THREAD;
 699   if (UseBiasedLocking) {
 700     BiasedLocking::revoke(current, obj);
 701     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 702   }
 703 
 704   markWord mark = obj->mark();
 705   if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {

 706     // Not inflated so there can't be any waiters to notify.
 707     return;
 708   }
 709   // The ObjectMonitor* can't be async deflated until ownership is
 710   // dropped by the calling thread.
 711   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_notify);
 712   monitor->notifyAll(CHECK);
 713 }
 714 
 715 // -----------------------------------------------------------------------------
 716 // Hash Code handling
 717 
 718 struct SharedGlobals {
 719   char         _pad_prefix[OM_CACHE_LINE_SIZE];
 720   // This is a highly shared mostly-read variable.
 721   // To avoid false-sharing it needs to be the sole occupant of a cache line.
 722   volatile int stw_random;
 723   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 724   // Hot RW variable -- Sequester to avoid false-sharing
 725   volatile int hc_sequence;
 726   DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 727 };
 728 
 729 static SharedGlobals GVars;
 730 
 731 static markWord read_stable_mark(oop obj) {
 732   markWord mark = obj->mark();
 733   if (!mark.is_being_inflated()) {
 734     return mark;       // normal fast-path return
 735   }
 736 
 737   int its = 0;
 738   for (;;) {
 739     markWord mark = obj->mark();
 740     if (!mark.is_being_inflated()) {
 741       return mark;    // normal fast-path return
 742     }
 743 
 744     // The object is being inflated by some other thread.
 745     // The caller of read_stable_mark() must wait for inflation to complete.
 746     // Avoid live-lock.
 747 
 748     ++its;
 749     if (its > 10000 || !os::is_MP()) {
 750       if (its & 1) {
 751         os::naked_yield();
 752       } else {
 753         // Note that the following code attenuates the livelock problem but is not

 828     // Marsaglia's xor-shift scheme with thread-specific state
 829     // This is probably the best overall implementation -- we'll
 830     // likely make this the default in future releases.
 831     unsigned t = current->_hashStateX;
 832     t ^= (t << 11);
 833     current->_hashStateX = current->_hashStateY;
 834     current->_hashStateY = current->_hashStateZ;
 835     current->_hashStateZ = current->_hashStateW;
 836     unsigned v = current->_hashStateW;
 837     v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
 838     current->_hashStateW = v;
 839     value = v;
 840   }
 841 
 842   value &= markWord::hash_mask;
 843   if (value == 0) value = 0xBAD;
 844   assert(value != markWord::no_hash, "invariant");
 845   return value;
 846 }
 847 





 848 intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) {
 849   if (UseBiasedLocking) {
 850     // NOTE: many places throughout the JVM do not expect a safepoint
 851     // to be taken here. However, we only ever bias Java instances and all
 852     // of the call sites of identity_hash that might revoke biases have
 853     // been checked to make sure they can handle a safepoint. The
 854     // added check of the bias pattern is to avoid useless calls to
 855     // thread-local storage.
 856     if (obj->mark().has_bias_pattern()) {
 857       // Handle for oop obj in case of STW safepoint
 858       Handle hobj(current, obj);
 859       if (SafepointSynchronize::is_at_safepoint()) {
 860         BiasedLocking::revoke_at_safepoint(hobj);
 861       } else {
 862         BiasedLocking::revoke(current->as_Java_thread(), hobj);
 863       }
 864       obj = hobj();
 865       assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
 866     }
 867   }

 901 
 902         // Separate load of dmw/header above from the loads in
 903         // is_being_async_deflated().
 904 
 905         // dmw/header and _contentions may get written by different threads.
 906         // Make sure to observe them in the same order when having several observers.
 907         OrderAccess::loadload_for_IRIW();
 908 
 909         if (monitor->is_being_async_deflated()) {
 910           // But we can't safely use the hash if we detect that async
 911           // deflation has occurred. So we attempt to restore the
 912           // header/dmw to the object's header so that we only retry
 913           // once if the deflater thread happens to be slow.
 914           monitor->install_displaced_markword_in_object(obj);
 915           continue;
 916         }
 917         return hash;
 918       }
 919       // Fall thru so we only have one place that installs the hash in
 920       // the ObjectMonitor.
 921     } else if (current->is_lock_owned((address)mark.locker())) {







 922       // This is a stack lock owned by the calling thread so fetch the
 923       // displaced markWord from the BasicLock on the stack.
 924       temp = mark.displaced_mark_helper();
 925       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
 926       hash = temp.hash();
 927       if (hash != 0) {                  // if it has a hash, just return it
 928         return hash;
 929       }
 930       // WARNING:
 931       // The displaced header in the BasicLock on a thread's stack
 932       // is strictly immutable. It CANNOT be changed in ANY cases.
 933       // So we have to inflate the stack lock into an ObjectMonitor
 934       // even if the current thread owns the lock. The BasicLock on
 935       // a thread's stack can be asynchronously read by other threads
 936       // during an inflate() call so any change to that stack memory
 937       // may not propagate to other threads correctly.
 938     }
 939 
 940     // Inflate the monitor to set the hash.
 941 

 982   return FastHashCode(Thread::current(), obj());
 983 }
 984 
 985 
 986 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* current,
 987                                                    Handle h_obj) {
 988   if (UseBiasedLocking) {
 989     BiasedLocking::revoke(current, h_obj);
 990     assert(!h_obj->mark().has_bias_pattern(), "biases should be revoked by now");
 991   }
 992 
 993   assert(current == JavaThread::current(), "Can only be called on current thread");
 994   oop obj = h_obj();
 995 
 996   markWord mark = read_stable_mark(obj);
 997 
 998   // Uncontended case, header points to stack
 999   if (mark.has_locker()) {
1000     return current->is_lock_owned((address)mark.locker());
1001   }






1002   // Contended case, header points to ObjectMonitor (tagged pointer)
1003   if (mark.has_monitor()) {
1004     // The first stage of async deflation does not affect any field
1005     // used by this comparison so the ObjectMonitor* is usable here.
1006     ObjectMonitor* monitor = mark.monitor();
1007     return monitor->is_entered(current) != 0;
1008   }
1009   // Unlocked case, header in place
1010   assert(mark.is_neutral(), "sanity check");
1011   return false;
1012 }
1013 
1014 // FIXME: jvmti should call this
1015 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
1016   if (UseBiasedLocking) {
1017     if (SafepointSynchronize::is_at_safepoint()) {
1018       BiasedLocking::revoke_at_safepoint(h_obj);
1019     } else {
1020       BiasedLocking::revoke(JavaThread::current(), h_obj);
1021     }
1022     assert(!h_obj->mark().has_bias_pattern(), "biases should be revoked by now");
1023   }
1024 
1025   oop obj = h_obj();
1026   address owner = NULL;
1027 
1028   markWord mark = read_stable_mark(obj);
1029 
1030   // Uncontended case, header points to stack
1031   if (mark.has_locker()) {
1032     owner = (address) mark.locker();




1033   }
1034 
1035   // Contended case, header points to ObjectMonitor (tagged pointer)
1036   else if (mark.has_monitor()) {
1037     // The first stage of async deflation does not affect any field
1038     // used by this comparison so the ObjectMonitor* is usable here.
1039     ObjectMonitor* monitor = mark.monitor();
1040     assert(monitor != NULL, "monitor should be non-null");
1041     owner = (address) monitor->owner();
1042   }
1043 
1044   if (owner != NULL) {
1045     // owning_thread_from_monitor_owner() may also return NULL here
1046     return Threads::owning_thread_from_monitor_owner(t_list, owner);
1047   }
1048 
1049   // Unlocked case, header in place
1050   // Cannot have assertion since this object may have been
1051   // locked by another thread when reaching here.
1052   // assert(mark.is_neutral(), "sanity check");
1053 
1054   return NULL;
1055 }
1056 
1057 // Visitors ...
1058 
1059 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure, JavaThread* thread) {
1060   MonitorList::Iterator iter = _in_use_list.iterator();
1061   while (iter.has_next()) {
1062     ObjectMonitor* mid = iter.next();
1063     if (mid->owner() != thread) {
1064       continue;
1065     }
1066     if (!mid->is_being_async_deflated() && mid->object_peek() != NULL) {
1067       // Only process with closure if the object is set.
1068 
1069       // monitors_iterate() is only called at a safepoint or when the
1070       // target thread is suspended or when the target thread is
1071       // operating on itself. The current closures in use today are
1072       // only interested in an owned ObjectMonitor and ownership
1073       // cannot be dropped under the calling contexts so the

1202 ObjectMonitor* ObjectSynchronizer::inflate(Thread* current, oop object,
1203                                            const InflateCause cause) {
1204   EventJavaMonitorInflate event;
1205 
1206   for (;;) {
1207     const markWord mark = object->mark();
1208     assert(!mark.has_bias_pattern(), "invariant");
1209 
1210     // The mark can be in one of the following states:
1211     // *  Inflated     - just return
1212     // *  Stack-locked - coerce it to inflated
1213     // *  INFLATING    - busy wait for conversion to complete
1214     // *  Neutral      - aggressively inflate the object.
1215     // *  BIASED       - Illegal.  We should never see this
1216 
1217     // CASE: inflated
1218     if (mark.has_monitor()) {
1219       ObjectMonitor* inf = mark.monitor();
1220       markWord dmw = inf->header();
1221       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());





1222       return inf;
1223     }
1224 
1225     // CASE: inflation in progress - inflating over a stack-lock.
1226     // Some other thread is converting from stack-locked to inflated.
1227     // Only that thread can complete inflation -- other threads must wait.
1228     // The INFLATING value is transient.
1229     // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
1230     // We could always eliminate polling by parking the thread on some auxiliary list.
1231     if (mark == markWord::INFLATING()) {



1232       read_stable_mark(object);
1233       continue;
1234     }
1235 
1236     // CASE: stack-locked
1237     // Could be stack-locked either by this thread or by some other thread.
1238     //
1239     // Note that we allocate the ObjectMonitor speculatively, _before_ attempting
1240     // to install INFLATING into the mark word.  We originally installed INFLATING,
1241     // allocated the ObjectMonitor, and then finally STed the address of the
1242     // ObjectMonitor into the mark.  This was correct, but artificially lengthened
1243     // the interval in which INFLATING appeared in the mark, thus increasing
1244     // the odds of inflation contention.
1245 
1246     LogStreamHandle(Trace, monitorinflation) lsh;










































1247 
1248     if (mark.has_locker()) {

1249       ObjectMonitor* m = new ObjectMonitor(object);
1250       // Optimistically prepare the ObjectMonitor - anticipate successful CAS
1251       // We do this before the CAS in order to minimize the length of time
1252       // in which INFLATING appears in the mark.
1253 
1254       markWord cmp = object->cas_set_mark(markWord::INFLATING(), mark);
1255       if (cmp != mark) {
1256         delete m;
1257         continue;       // Interference -- just retry
1258       }
1259 
1260       // We've successfully installed INFLATING (0) into the mark-word.
1261       // This is the only case where 0 will appear in a mark-word.
1262       // Only the singular thread that successfully swings the mark-word
1263       // to 0 can perform (or more precisely, complete) inflation.
1264       //
1265       // Why do we CAS a 0 into the mark-word instead of just CASing the
1266       // mark-word from the stack-locked value directly to the new inflated state?
1267       // Consider what happens when a thread unlocks a stack-locked object.
1268       // It attempts to use CAS to swing the displaced header value from the

1301       // that it has stack-locked -- as might happen in wait() -- directly
1302       // with CAS.  That is, we can avoid the xchg-NULL .... ST idiom.
1303       m->set_owner_from(NULL, mark.locker());
1304       // TODO-FIXME: assert BasicLock->dhw != 0.
1305 
1306       // Must preserve store ordering. The monitor state must
1307       // be stable at the time of publishing the monitor address.
1308       guarantee(object->mark() == markWord::INFLATING(), "invariant");
1309       // Release semantics so that above set_object() is seen first.
1310       object->release_set_mark(markWord::encode(m));
1311 
1312       // Once ObjectMonitor is configured and the object is associated
1313       // with the ObjectMonitor, it is safe to allow async deflation:
1314       _in_use_list.add(m);
1315 
1316       // Hopefully the performance counters are allocated on distinct cache lines
1317       // to avoid false sharing on MP systems ...
1318       OM_PERFDATA_OP(Inflations, inc());
1319       if (log_is_enabled(Trace, monitorinflation)) {
1320         ResourceMark rm(current);
1321         lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark="
1322                      INTPTR_FORMAT ", type='%s'", p2i(object),
1323                      object->mark().value(), object->klass()->external_name());
1324       }
1325       if (event.should_commit()) {
1326         post_monitor_inflate_event(&event, object, cause);
1327       }
1328       return m;
1329     }
1330 
1331     // CASE: neutral
1332     // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1333     // If we know we're inflating for entry it's better to inflate by swinging a
1334     // pre-locked ObjectMonitor pointer into the object header.   A successful
1335     // CAS inflates the object *and* confers ownership to the inflating thread.
1336     // In the current implementation we use a 2-step mechanism where we CAS()
1337     // to inflate and then CAS() again to try to swing _owner from NULL to current.
1338     // An inflateTry() method that we could call from enter() would be useful.
1339 
1340     // Catch if the object's header is not neutral (not locked and
1341     // not marked is what we care about here).

1421     if (current->is_Java_thread()) {
1422       // A JavaThread must check for a safepoint/handshake and honor it.
1423       chk_for_block_req(current->as_Java_thread(), "deflation", "deflated_count",
1424                         deflated_count, ls, timer_p);
1425     }
1426   }
1427 
1428   return deflated_count;
1429 }
1430 
1431 class HandshakeForDeflation : public HandshakeClosure {
1432  public:
1433   HandshakeForDeflation() : HandshakeClosure("HandshakeForDeflation") {}
1434 
1435   void do_thread(Thread* thread) {
1436     log_trace(monitorinflation)("HandshakeForDeflation::do_thread: thread="
1437                                 INTPTR_FORMAT, p2i(thread));
1438   }
1439 };
1440 










1441 // This function is called by the MonitorDeflationThread to deflate
1442 // ObjectMonitors. It is also called via do_final_audit_and_print_stats()
1443 // by the VMThread.
1444 size_t ObjectSynchronizer::deflate_idle_monitors() {
1445   Thread* current = Thread::current();
1446   if (current->is_Java_thread()) {
1447     // The async deflation request has been processed.
1448     _last_async_deflation_time_ns = os::javaTimeNanos();
1449     set_is_async_deflation_requested(false);
1450   }
1451 
1452   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1453   LogStreamHandle(Info, monitorinflation) lsh_info;
1454   LogStream* ls = NULL;
1455   if (log_is_enabled(Debug, monitorinflation)) {
1456     ls = &lsh_debug;
1457   } else if (log_is_enabled(Info, monitorinflation)) {
1458     ls = &lsh_info;
1459   }
1460 

1473     // deflated, BUT the MonitorDeflationThread blocked for the final
1474     // safepoint during unlinking.
1475 
1476     // Unlink deflated ObjectMonitors from the in-use list.
1477     ResourceMark rm;
1478     GrowableArray<ObjectMonitor*> delete_list((int)deflated_count);
1479     size_t unlinked_count = _in_use_list.unlink_deflated(current, ls, &timer,
1480                                                          &delete_list);
1481     if (current->is_Java_thread()) {
1482       if (ls != NULL) {
1483         timer.stop();
1484         ls->print_cr("before handshaking: unlinked_count=" SIZE_FORMAT
1485                      ", in_use_list stats: ceiling=" SIZE_FORMAT ", count="
1486                      SIZE_FORMAT ", max=" SIZE_FORMAT,
1487                      unlinked_count, in_use_list_ceiling(),
1488                      _in_use_list.count(), _in_use_list.max());
1489       }
1490 
1491       // A JavaThread needs to handshake in order to safely free the
1492       // ObjectMonitors that were deflated in this cycle.



1493       HandshakeForDeflation hfd_hc;
1494       Handshake::execute(&hfd_hc);


1495 
1496       if (ls != NULL) {
1497         ls->print_cr("after handshaking: in_use_list stats: ceiling="
1498                      SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1499                      in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max());
1500         timer.start();
1501       }
1502     }
1503 
1504     // After the handshake, safely free the ObjectMonitors that were
1505     // deflated in this cycle.
1506     size_t deleted_count = 0;
1507     for (ObjectMonitor* monitor: delete_list) {
1508       delete monitor;
1509       deleted_count++;
1510 
1511       if (current->is_Java_thread()) {
1512         // A JavaThread must check for a safepoint/handshake and honor it.
1513         chk_for_block_req(current->as_Java_thread(), "deletion", "deleted_count",
1514                           deleted_count, ls, &timer);

   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 

 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;

 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();

 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   }

 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

 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   }

 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 

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

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

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).

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 

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);
< prev index next >