< prev index next >

src/hotspot/share/runtime/synchronizer.cpp

Print this page
rev 54612 : Checkpoint latest preliminary review patches for full OpenJDK review; merge with 8222295.patch.
rev 54613 : imported patch dcubed.monitor_deflate_conc.v2.01
rev 54614 : imported patch dcubed.monitor_deflate_conc.v2.02
rev 54615 : imported patch dcubed.monitor_deflate_conc.v2.03


 107 #endif // ndef DTRACE_ENABLED
 108 
 109 // This exists only as a workaround of dtrace bug 6254741
 110 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
 111   DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
 112   return 0;
 113 }
 114 
 115 #define NINFLATIONLOCKS 256
 116 static volatile intptr_t gInflationLocks[NINFLATIONLOCKS];
 117 
 118 // global list of blocks of monitors
 119 PaddedEnd<ObjectMonitor> * volatile ObjectSynchronizer::gBlockList = NULL;
 120 // global monitor free list
 121 ObjectMonitor * volatile ObjectSynchronizer::gFreeList  = NULL;
 122 // global monitor in-use list, for moribund threads,
 123 // monitors they inflated need to be scanned for deflation
 124 ObjectMonitor * volatile ObjectSynchronizer::gOmInUseList  = NULL;
 125 // count of entries in gOmInUseList
 126 int ObjectSynchronizer::gOmInUseCount = 0;


 127 
 128 static volatile intptr_t gListLock = 0;      // protects global monitor lists
 129 static volatile int gMonitorFreeCount  = 0;  // # on gFreeList
 130 static volatile int gMonitorPopulation = 0;  // # Extant -- in circulation
 131 
 132 #define CHAINMARKER (cast_to_oop<intptr_t>(-1))
 133 
 134 
 135 // =====================> Quick functions
 136 
 137 // The quick_* forms are special fast-path variants used to improve
 138 // performance.  In the simplest case, a "quick_*" implementation could
 139 // simply return false, in which case the caller will perform the necessary
 140 // state transitions and call the slow-path form.
 141 // The fast-path is designed to handle frequently arising cases in an efficient
 142 // manner and is just a degenerate "optimistic" variant of the slow-path.
 143 // returns true  -- to indicate the call was satisfied.
 144 // returns false -- to indicate the call needs the services of the slow-path.
 145 // A no-loitering ordinance is in effect for code in the quick_* family
 146 // operators: safepoints or indefinite blocking (blocking that might span a


 193   }
 194 
 195   // biased locking and any other IMS exception states take the slow-path
 196   return false;
 197 }
 198 
 199 
 200 // The LockNode emitted directly at the synchronization site would have
 201 // been too big if it were to have included support for the cases of inflated
 202 // recursive enter and exit, so they go here instead.
 203 // Note that we can't safely call AsyncPrintJavaStack() from within
 204 // quick_enter() as our thread state remains _in_Java.
 205 
 206 bool ObjectSynchronizer::quick_enter(oop obj, Thread * Self,
 207                                      BasicLock * lock) {
 208   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 209   assert(Self->is_Java_thread(), "invariant");
 210   assert(((JavaThread *) Self)->thread_state() == _thread_in_Java, "invariant");
 211   NoSafepointVerifier nsv;
 212   if (obj == NULL) return false;       // Need to throw NPE


 213   const markOop mark = obj->mark();
 214 
 215   if (mark->has_monitor()) {
 216     ObjectMonitor * const m = mark->monitor();






 217     assert(oopDesc::equals((oop) m->object(), obj), "invariant");
 218     Thread * const owner = (Thread *) m->_owner;
 219 
 220     // Lock contention and Transactional Lock Elision (TLE) diagnostics
 221     // and observability
 222     // Case: light contention possibly amenable to TLE
 223     // Case: TLE inimical operations such as nested/recursive synchronization
 224 
 225     if (owner == Self) {
 226       m->_recursions++;
 227       return true;
 228     }
 229 
 230     // This Java Monitor is inflated so obj's header will never be
 231     // displaced to this thread's BasicLock. Make the displaced header
 232     // non-NULL so this BasicLock is not seen as recursive nor as
 233     // being locked. We do this unconditionally so that this thread's
 234     // BasicLock cannot be mis-interpreted by any stack walkers. For
 235     // performance reasons, stack walkers generally first check for
 236     // Biased Locking in the object's header, the second check is for
 237     // stack-locking in the object's header, the third check is for
 238     // recursive stack-locking in the displaced header in the BasicLock,
 239     // and last are the inflated Java Monitor (ObjectMonitor) checks.
 240     lock->set_displaced_header(markOopDesc::unused_mark());
 241 
 242     if (owner == NULL && Atomic::replace_if_null(Self, &(m->_owner))) {
 243       assert(m->_recursions == 0, "invariant");
 244       assert(m->_owner == Self, "invariant");
 245       return true;
 246     }
 247   }


 248 
 249   // Note that we could inflate in quick_enter.
 250   // This is likely a useful optimization
 251   // Critically, in quick_enter() we must not:
 252   // -- perform bias revocation, or
 253   // -- block indefinitely, or
 254   // -- reach a safepoint
 255 
 256   return false;        // revert to slow-path
 257 }
 258 
 259 // -----------------------------------------------------------------------------
 260 //  Fast Monitor Enter/Exit
 261 // This the fast monitor enter. The interpreter and compiler use
 262 // some assembly copies of this code. Make sure update those code
 263 // if the following function is changed. The implementation is
 264 // extremely sensitive to race condition. Be careful.
 265 
 266 void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock,
 267                                     bool attempt_rebias, TRAPS) {


 310         // does not own the Java Monitor.
 311         ObjectMonitor * m = mark->monitor();
 312         assert(((oop)(m->object()))->mark() == mark, "invariant");
 313         assert(m->is_entered(THREAD), "invariant");
 314       }
 315     }
 316 #endif
 317     return;
 318   }
 319 
 320   if (mark == (markOop) lock) {
 321     // If the object is stack-locked by the current thread, try to
 322     // swing the displaced header from the BasicLock back to the mark.
 323     assert(dhw->is_neutral(), "invariant");
 324     if (object->cas_set_mark(dhw, mark) == mark) {
 325       return;
 326     }
 327   }
 328 
 329   // We have to take the slow-path of possible inflation and then exit.
 330   inflate(THREAD, object, inflate_cause_vm_internal)->exit(true, THREAD);


 331 }
 332 
 333 // -----------------------------------------------------------------------------
 334 // Interpreter/Compiler Slow Case
 335 // This routine is used to handle interpreter/compiler slow case
 336 // We don't need to use fast path here, because it must have been
 337 // failed in the interpreter/compiler code.
 338 void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) {
 339   markOop mark = obj->mark();
 340   assert(!mark->has_bias_pattern(), "should not see bias pattern here");
 341 
 342   if (mark->is_neutral()) {
 343     // Anticipate successful CAS -- the ST of the displaced mark must
 344     // be visible <= the ST performed by the CAS.
 345     lock->set_displaced_header(mark);
 346     if (mark == obj()->cas_set_mark((markOop) lock, mark)) {
 347       return;
 348     }
 349     // Fall through to inflate() ...
 350   } else if (mark->has_locker() &&
 351              THREAD->is_lock_owned((address)mark->locker())) {
 352     assert(lock != mark->locker(), "must not re-lock the same lock");
 353     assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock");
 354     lock->set_displaced_header(NULL);
 355     return;
 356   }
 357 
 358   // The object header will never be displaced to this lock,
 359   // so it does not matter what the value is, except that it
 360   // must be non-zero to avoid looking like a re-entrant lock,
 361   // and must not look locked either.
 362   lock->set_displaced_header(markOopDesc::unused_mark());
 363   inflate(THREAD, obj(), inflate_cause_monitor_enter)->enter(THREAD);


 364 }
 365 
 366 // This routine is used to handle interpreter/compiler slow case
 367 // We don't need to use fast path here, because it must have
 368 // failed in the interpreter/compiler code. Simply use the heavy
 369 // weight monitor should be ok, unless someone find otherwise.
 370 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
 371   fast_exit(object, lock, THREAD);
 372 }
 373 
 374 // -----------------------------------------------------------------------------
 375 // Class Loader  support to workaround deadlocks on the class loader lock objects
 376 // Also used by GC
 377 // complete_exit()/reenter() are used to wait on a nested lock
 378 // i.e. to give up an outer lock completely and then re-enter
 379 // Used when holding nested locks - lock acquisition order: lock1 then lock2
 380 //  1) complete_exit lock1 - saving recursion count
 381 //  2) wait on lock2
 382 //  3) when notified on lock2, unlock lock2
 383 //  4) reenter lock1 with original recursion count
 384 //  5) lock lock2
 385 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 386 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) {
 387   if (UseBiasedLocking) {
 388     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 389     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 390   }
 391 
 392   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_vm_internal);
 393 
 394   return monitor->complete_exit(THREAD);

 395 }
 396 
 397 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 398 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) {
 399   if (UseBiasedLocking) {
 400     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 401     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 402   }
 403 
 404   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_vm_internal);
 405 
 406   monitor->reenter(recursion, THREAD);
 407 }
 408 // -----------------------------------------------------------------------------
 409 // JNI locks on java objects
 410 // NOTE: must use heavy weight monitor to handle jni monitor enter
 411 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) {
 412   // the current locking is from JNI instead of Java code
 413   if (UseBiasedLocking) {
 414     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 415     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 416   }
 417   THREAD->set_current_pending_monitor_is_from_java(false);
 418   inflate(THREAD, obj(), inflate_cause_jni_enter)->enter(THREAD);


 419   THREAD->set_current_pending_monitor_is_from_java(true);
 420 }
 421 
 422 // NOTE: must use heavy weight monitor to handle jni monitor exit
 423 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
 424   if (UseBiasedLocking) {
 425     Handle h_obj(THREAD, obj);
 426     BiasedLocking::revoke_and_rebias(h_obj, false, THREAD);
 427     obj = h_obj();
 428   }
 429   assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 430 
 431   ObjectMonitor* monitor = inflate(THREAD, obj, inflate_cause_jni_exit);


 432   // If this thread has locked the object, exit the monitor.  Note:  can't use
 433   // monitor->check(CHECK); must exit even if an exception is pending.
 434   if (monitor->check(THREAD)) {
 435     monitor->exit(true, THREAD);
 436   }
 437 }
 438 
 439 // -----------------------------------------------------------------------------
 440 // Internal VM locks on java objects
 441 // standard constructor, allows locking failures
 442 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) {
 443   _dolock = doLock;
 444   _thread = thread;
 445   debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);)
 446   _obj = obj;
 447 
 448   if (_dolock) {
 449     ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread);
 450   }
 451 }
 452 
 453 ObjectLocker::~ObjectLocker() {
 454   if (_dolock) {
 455     ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread);
 456   }
 457 }
 458 
 459 
 460 // -----------------------------------------------------------------------------
 461 //  Wait/Notify/NotifyAll
 462 // NOTE: must use heavy weight monitor to handle wait()
 463 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 464   if (UseBiasedLocking) {
 465     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 466     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 467   }
 468   if (millis < 0) {
 469     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 470   }
 471   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_wait);


 472 
 473   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);
 474   monitor->wait(millis, true, THREAD);
 475 
 476   // This dummy call is in place to get around dtrace bug 6254741.  Once
 477   // that's fixed we can uncomment the following line, remove the call
 478   // and change this function back into a "void" func.
 479   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 480   return dtrace_waited_probe(monitor, obj, THREAD);

 481 }
 482 
 483 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) {
 484   if (UseBiasedLocking) {
 485     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 486     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 487   }
 488   if (millis < 0) {
 489     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 490   }
 491   inflate(THREAD, obj(), inflate_cause_wait)->wait(millis, false, THREAD);


 492 }
 493 
 494 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 495   if (UseBiasedLocking) {
 496     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 497     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 498   }
 499 
 500   markOop mark = obj->mark();
 501   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
 502     return;
 503   }
 504   inflate(THREAD, obj(), inflate_cause_notify)->notify(THREAD);


 505 }
 506 
 507 // NOTE: see comment of notify()
 508 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 509   if (UseBiasedLocking) {
 510     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 511     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 512   }
 513 
 514   markOop mark = obj->mark();
 515   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
 516     return;
 517   }
 518   inflate(THREAD, obj(), inflate_cause_notify)->notifyAll(THREAD);


 519 }
 520 
 521 // -----------------------------------------------------------------------------
 522 // Hash Code handling
 523 //
 524 // Performance concern:
 525 // OrderAccess::storestore() calls release() which at one time stored 0
 526 // into the global volatile OrderAccess::dummy variable. This store was
 527 // unnecessary for correctness. Many threads storing into a common location
 528 // causes considerable cache migration or "sloshing" on large SMP systems.
 529 // As such, I avoided using OrderAccess::storestore(). In some cases
 530 // OrderAccess::fence() -- which incurs local latency on the executing
 531 // processor -- is a better choice as it scales on SMP systems.
 532 //
 533 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for
 534 // a discussion of coherency costs. Note that all our current reference
 535 // platforms provide strong ST-ST order, so the issue is moot on IA32,
 536 // x64, and SPARC.
 537 //
 538 // As a general policy we use "volatile" to control compiler-based reordering


 692       Handle hobj(Self, obj);
 693       // Relaxing assertion for bug 6320749.
 694       assert(Universe::verify_in_progress() ||
 695              !SafepointSynchronize::is_at_safepoint(),
 696              "biases should not be seen by VM thread here");
 697       BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
 698       obj = hobj();
 699       assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 700     }
 701   }
 702 
 703   // hashCode() is a heap mutator ...
 704   // Relaxing assertion for bug 6320749.
 705   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
 706          !SafepointSynchronize::is_at_safepoint(), "invariant");
 707   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
 708          Self->is_Java_thread() , "invariant");
 709   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
 710          ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant");
 711 

 712   ObjectMonitor* monitor = NULL;
 713   markOop temp, test;
 714   intptr_t hash;
 715   markOop mark = ReadStableMark(obj);
 716 
 717   // object should remain ineligible for biased locking
 718   assert(!mark->has_bias_pattern(), "invariant");
 719 
 720   if (mark->is_neutral()) {
 721     hash = mark->hash();              // this is a normal header
 722     if (hash != 0) {                  // if it has hash, just return it
 723       return hash;
 724     }
 725     hash = get_next_hash(Self, obj);  // allocate a new hash code
 726     temp = mark->copy_set_hash(hash); // merge the hash code into header
 727     // use (machine word version) atomic operation to install the hash
 728     test = obj->cas_set_mark(temp, mark);
 729     if (test == mark) {
 730       return hash;
 731     }
 732     // If atomic operation failed, we must inflate the header
 733     // into heavy weight monitor. We could add more code here
 734     // for fast path, but it does not worth the complexity.
 735   } else if (mark->has_monitor()) {
 736     monitor = mark->monitor();






 737     temp = monitor->header();
 738     assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
 739     hash = temp->hash();
 740     if (hash != 0) {
 741       return hash;
 742     }
 743     // Skip to the following code to reduce code size
 744   } else if (Self->is_lock_owned((address)mark->locker())) {
 745     temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
 746     assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
 747     hash = temp->hash();              // by current thread, check if the displaced
 748     if (hash != 0) {                  // header contains hash code
 749       return hash;
 750     }
 751     // WARNING:
 752     // The displaced header in the BasicLock on a thread's stack
 753     // is strictly immutable. It CANNOT be changed in ANY cases.
 754     // So we have to inflate the stack lock into an ObjectMonitor
 755     // even if the current thread owns the lock. The BasicLock on
 756     // a thread's stack can be asynchronously read by other threads
 757     // during an inflate() call so any change to that stack memory
 758     // may not propagate to other threads correctly.
 759   }
 760 
 761   // Inflate the monitor to set hash code
 762   monitor = inflate(Self, obj, inflate_cause_hash_code);


 763   // Load displaced header and check it has hash code
 764   mark = monitor->header();
 765   assert(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark));
 766   hash = mark->hash();
 767   if (hash == 0) {
 768     hash = get_next_hash(Self, obj);
 769     temp = mark->copy_set_hash(hash); // merge hash code into header
 770     assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
 771     test = Atomic::cmpxchg(temp, monitor->header_addr(), mark);
 772     if (test != mark) {
 773       // The only update to the ObjectMonitor's header/dmw field
 774       // is to merge in the hash code. If someone adds a new usage
 775       // of the header/dmw field, please update this code.





 776       hash = test->hash();
 777       assert(test->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(test));
 778       assert(hash != 0, "Trivial unexpected object/monitor header usage.");
 779     }
 780   }
 781   // We finally get the hash
 782   return hash;

 783 }
 784 
 785 // Deprecated -- use FastHashCode() instead.
 786 
 787 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
 788   return FastHashCode(Thread::current(), obj());
 789 }
 790 
 791 
 792 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread,
 793                                                    Handle h_obj) {
 794   if (UseBiasedLocking) {
 795     BiasedLocking::revoke_and_rebias(h_obj, false, thread);
 796     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 797   }
 798 
 799   assert(thread == JavaThread::current(), "Can only be called on current thread");
 800   oop obj = h_obj();
 801 

 802   markOop mark = ReadStableMark(obj);
 803 
 804   // Uncontended case, header points to stack
 805   if (mark->has_locker()) {
 806     return thread->is_lock_owned((address)mark->locker());
 807   }
 808   // Contended case, header points to ObjectMonitor (tagged pointer)
 809   if (mark->has_monitor()) {
 810     ObjectMonitor* monitor = mark->monitor();
 811     return monitor->is_entered(thread) != 0;






 812   }
 813   // Unlocked case, header in place
 814   assert(mark->is_neutral(), "sanity check");
 815   return false;

 816 }
 817 
 818 // Be aware of this method could revoke bias of the lock object.
 819 // This method queries the ownership of the lock handle specified by 'h_obj'.
 820 // If the current thread owns the lock, it returns owner_self. If no
 821 // thread owns the lock, it returns owner_none. Otherwise, it will return
 822 // owner_other.
 823 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership
 824 (JavaThread *self, Handle h_obj) {
 825   // The caller must beware this method can revoke bias, and
 826   // revocation can result in a safepoint.
 827   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 828   assert(self->thread_state() != _thread_blocked, "invariant");
 829 
 830   // Possible mark states: neutral, biased, stack-locked, inflated
 831 
 832   if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) {
 833     // CASE: biased
 834     BiasedLocking::revoke_and_rebias(h_obj, false, self);
 835     assert(!h_obj->mark()->has_bias_pattern(),
 836            "biases should be revoked by now");
 837   }
 838 
 839   assert(self == JavaThread::current(), "Can only be called on current thread");
 840   oop obj = h_obj();


 841   markOop mark = ReadStableMark(obj);
 842 
 843   // CASE: stack-locked.  Mark points to a BasicLock on the owner's stack.
 844   if (mark->has_locker()) {
 845     return self->is_lock_owned((address)mark->locker()) ?
 846       owner_self : owner_other;
 847   }
 848 
 849   // CASE: inflated. Mark (tagged pointer) points to an ObjectMonitor.
 850   // The Object:ObjectMonitor relationship is stable as long as we're
 851   // not at a safepoint.
 852   if (mark->has_monitor()) {
 853     void * owner = mark->monitor()->_owner;







 854     if (owner == NULL) return owner_none;
 855     return (owner == self ||
 856             self->is_lock_owned((address)owner)) ? owner_self : owner_other;
 857   }
 858 
 859   // CASE: neutral
 860   assert(mark->is_neutral(), "sanity check");
 861   return owner_none;           // it's unlocked

 862 }
 863 
 864 // FIXME: jvmti should call this
 865 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
 866   if (UseBiasedLocking) {
 867     if (SafepointSynchronize::is_at_safepoint()) {
 868       BiasedLocking::revoke_at_safepoint(h_obj);
 869     } else {
 870       BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current());
 871     }
 872     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 873   }
 874 
 875   oop obj = h_obj();
 876   address owner = NULL;
 877 


 878   markOop mark = ReadStableMark(obj);
 879 
 880   // Uncontended case, header points to stack
 881   if (mark->has_locker()) {
 882     owner = (address) mark->locker();
 883   }
 884 
 885   // Contended case, header points to ObjectMonitor (tagged pointer)
 886   else if (mark->has_monitor()) {
 887     ObjectMonitor* monitor = mark->monitor();






 888     assert(monitor != NULL, "monitor should be non-null");
 889     owner = (address) monitor->owner();
 890   }
 891 
 892   if (owner != NULL) {
 893     // owning_thread_from_monitor_owner() may also return NULL here
 894     return Threads::owning_thread_from_monitor_owner(t_list, owner);
 895   }
 896 
 897   // Unlocked case, header in place
 898   // Cannot have assertion since this object may have been
 899   // locked by another thread when reaching here.
 900   // assert(mark->is_neutral(), "sanity check");
 901 
 902   return NULL;

 903 }
 904 
 905 // Visitors ...
 906 
 907 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) {
 908   PaddedEnd<ObjectMonitor> * block = OrderAccess::load_acquire(&gBlockList);
 909   while (block != NULL) {
 910     assert(block->object() == CHAINMARKER, "must be a block header");
 911     for (int i = _BLOCKSIZE - 1; i > 0; i--) {
 912       ObjectMonitor* mid = (ObjectMonitor *)(block + i);
 913       oop object = (oop)mid->object();
 914       if (object != NULL) {










 915         closure->do_monitor(mid);
 916       }
 917     }
 918     block = (PaddedEnd<ObjectMonitor> *)block->FreeNext;
 919   }
 920 }
 921 
 922 // Get the next block in the block list.
 923 static inline PaddedEnd<ObjectMonitor>* next(PaddedEnd<ObjectMonitor>* block) {
 924   assert(block->object() == CHAINMARKER, "must be a block header");
 925   block = (PaddedEnd<ObjectMonitor>*) block->FreeNext;
 926   assert(block == NULL || block->object() == CHAINMARKER, "must be a block header");
 927   return block;
 928 }
 929 
 930 static bool monitors_used_above_threshold() {
 931   if (gMonitorPopulation == 0) {
 932     return false;
 933   }
 934   int monitors_used = gMonitorPopulation - gMonitorFreeCount;


1005 // See also: GuaranteedSafepointInterval
1006 //
1007 // The current implementation uses asynchronous VM operations.
1008 
1009 static void InduceScavenge(Thread * Self, const char * Whence) {
1010   // Induce STW safepoint to trim monitors
1011   // Ultimately, this results in a call to deflate_idle_monitors() in the near future.
1012   // More precisely, trigger an asynchronous STW safepoint as the number
1013   // of active monitors passes the specified threshold.
1014   // TODO: assert thread state is reasonable
1015 
1016   if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) {
1017     // Induce a 'null' safepoint to scavenge monitors
1018     // Must VM_Operation instance be heap allocated as the op will be enqueue and posted
1019     // to the VMthread and have a lifespan longer than that of this activation record.
1020     // The VMThread will delete the op when completed.
1021     VMThread::execute(new VM_ScavengeMonitors());
1022   }
1023 }
1024 
1025 ObjectMonitor* ObjectSynchronizer::omAlloc(Thread * Self) {

1026   // A large MAXPRIVATE value reduces both list lock contention
1027   // and list coherency traffic, but also tends to increase the
1028   // number of objectMonitors in circulation as well as the STW
1029   // scavenge costs.  As usual, we lean toward time in space-time
1030   // tradeoffs.
1031   const int MAXPRIVATE = 1024;














1032   for (;;) {
1033     ObjectMonitor * m;
1034 
1035     // 1: try to allocate from the thread's local omFreeList.
1036     // Threads will attempt to allocate first from their local list, then
1037     // from the global list, and only after those attempts fail will the thread
1038     // attempt to instantiate new monitors.   Thread-local free lists take
1039     // heat off the gListLock and improve allocation latency, as well as reducing
1040     // coherency traffic on the shared global list.
1041     m = Self->omFreeList;
1042     if (m != NULL) {
1043       Self->omFreeList = m->FreeNext;
1044       Self->omFreeCount--;
1045       guarantee(m->object() == NULL, "invariant");

1046       m->FreeNext = Self->omInUseList;
1047       Self->omInUseList = m;
1048       Self->omInUseCount++;
1049       return m;
1050     }
1051 
1052     // 2: try to allocate from the global gFreeList
1053     // CONSIDER: use muxTry() instead of muxAcquire().
1054     // If the muxTry() fails then drop immediately into case 3.
1055     // If we're using thread-local free lists then try
1056     // to reprovision the caller's free list.
1057     if (gFreeList != NULL) {
1058       // Reprovision the thread's omFreeList.
1059       // Use bulk transfers to reduce the allocation rate and heat
1060       // on various locks.
1061       Thread::muxAcquire(&gListLock, "omAlloc(1)");
1062       for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL;) {
1063         gMonitorFreeCount--;
1064         ObjectMonitor * take = gFreeList;
1065         gFreeList = take->FreeNext;
1066         guarantee(take->object() == NULL, "invariant");














1067         guarantee(!take->is_busy(), "invariant");
1068         take->Recycle();

1069         omRelease(Self, take, false);
1070       }
1071       Thread::muxRelease(&gListLock);
1072       Self->omFreeProvision += 1 + (Self->omFreeProvision/2);
1073       if (Self->omFreeProvision > MAXPRIVATE) Self->omFreeProvision = MAXPRIVATE;
1074 
1075       const int mx = MonitorBound;
1076       if (mx > 0 && (gMonitorPopulation-gMonitorFreeCount) > mx) {
1077         // We can't safely induce a STW safepoint from omAlloc() as our thread
1078         // state may not be appropriate for such activities and callers may hold
1079         // naked oops, so instead we defer the action.
1080         InduceScavenge(Self, "omAlloc");
1081       }
1082       continue;
1083     }
1084 
1085     // 3: allocate a block of new ObjectMonitors
1086     // Both the local and global free lists are empty -- resort to malloc().
1087     // In the current implementation objectMonitors are TSM - immortal.
1088     // Ideally, we'd write "new ObjectMonitor[_BLOCKSIZE], but we want


1101 
1102     // NOTE: (almost) no way to recover if allocation failed.
1103     // We might be able to induce a STW safepoint and scavenge enough
1104     // objectMonitors to permit progress.
1105     if (temp == NULL) {
1106       vm_exit_out_of_memory(neededsize, OOM_MALLOC_ERROR,
1107                             "Allocate ObjectMonitors");
1108     }
1109     (void)memset((void *) temp, 0, neededsize);
1110 
1111     // Format the block.
1112     // initialize the linked list, each monitor points to its next
1113     // forming the single linked free list, the very first monitor
1114     // will points to next block, which forms the block list.
1115     // The trick of using the 1st element in the block as gBlockList
1116     // linkage should be reconsidered.  A better implementation would
1117     // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; }
1118 
1119     for (int i = 1; i < _BLOCKSIZE; i++) {
1120       temp[i].FreeNext = (ObjectMonitor *)&temp[i+1];

1121     }
1122 
1123     // terminate the last monitor as the end of list
1124     temp[_BLOCKSIZE - 1].FreeNext = NULL;
1125 
1126     // Element [0] is reserved for global list linkage
1127     temp[0].set_object(CHAINMARKER);
1128 
1129     // Consider carving out this thread's current request from the
1130     // block in hand.  This avoids some lock traffic and redundant
1131     // list activity.
1132 
1133     // Acquire the gListLock to manipulate gBlockList and gFreeList.
1134     // An Oyama-Taura-Yonezawa scheme might be more efficient.
1135     Thread::muxAcquire(&gListLock, "omAlloc(2)");
1136     gMonitorPopulation += _BLOCKSIZE-1;
1137     gMonitorFreeCount += _BLOCKSIZE-1;
1138 
1139     // Add the new block to the list of extant blocks (gBlockList).
1140     // The very first objectMonitor in a block is reserved and dedicated.


1143     // There are lock-free uses of gBlockList so make sure that
1144     // the previous stores happen before we update gBlockList.
1145     OrderAccess::release_store(&gBlockList, temp);
1146 
1147     // Add the new string of objectMonitors to the global free list
1148     temp[_BLOCKSIZE - 1].FreeNext = gFreeList;
1149     gFreeList = temp + 1;
1150     Thread::muxRelease(&gListLock);
1151   }
1152 }
1153 
1154 // Place "m" on the caller's private per-thread omFreeList.
1155 // In practice there's no need to clamp or limit the number of
1156 // monitors on a thread's omFreeList as the only time we'll call
1157 // omRelease is to return a monitor to the free list after a CAS
1158 // attempt failed.  This doesn't allow unbounded #s of monitors to
1159 // accumulate on a thread's free list.
1160 //
1161 // Key constraint: all ObjectMonitors on a thread's free list and the global
1162 // free list must have their object field set to null. This prevents the
1163 // scavenger -- deflate_monitor_list() -- from reclaiming them.

1164 
1165 void ObjectSynchronizer::omRelease(Thread * Self, ObjectMonitor * m,
1166                                    bool fromPerThreadAlloc) {
1167   guarantee(m->header() == NULL, "invariant");
1168   guarantee(m->object() == NULL, "invariant");
1169   guarantee(((m->is_busy()|m->_recursions) == 0), "freeing in-use monitor");

1170   // Remove from omInUseList
1171   if (fromPerThreadAlloc) {
1172     ObjectMonitor* cur_mid_in_use = NULL;
1173     bool extracted = false;
1174     for (ObjectMonitor* mid = Self->omInUseList; mid != NULL; cur_mid_in_use = mid, mid = mid->FreeNext) {
1175       if (m == mid) {
1176         // extract from per-thread in-use list
1177         if (mid == Self->omInUseList) {
1178           Self->omInUseList = mid->FreeNext;
1179         } else if (cur_mid_in_use != NULL) {
1180           cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1181         }
1182         extracted = true;
1183         Self->omInUseCount--;
1184         break;
1185       }
1186     }
1187     assert(extracted, "Should have extracted from in-use list");
1188   }
1189 
1190   // FreeNext is used for both omInUseList and omFreeList, so clear old before setting new
1191   m->FreeNext = Self->omFreeList;

1192   Self->omFreeList = m;
1193   Self->omFreeCount++;
1194 }
1195 
1196 // Return the monitors of a moribund thread's local free list to
1197 // the global free list.  Typically a thread calls omFlush() when
1198 // it's dying.  We could also consider having the VM thread steal
1199 // monitors from threads that have not run java code over a few
1200 // consecutive STW safepoints.  Relatedly, we might decay
1201 // omFreeProvision at STW safepoints.
1202 //
1203 // Also return the monitors of a moribund thread's omInUseList to
1204 // a global gOmInUseList under the global list lock so these
1205 // will continue to be scanned.
1206 //
1207 // We currently call omFlush() from Threads::remove() _before the thread
1208 // has been excised from the thread list and is no longer a mutator.
1209 // This means that omFlush() cannot run concurrently with a safepoint and
1210 // interleave with the deflate_idle_monitors scavenge operator. In particular,
1211 // this ensures that the thread's monitors are scanned by a GC safepoint,
1212 // either via Thread::oops_do() (if safepoint happens before omFlush()) or via
1213 // ObjectSynchronizer::oops_do() (if it happens after omFlush() and the thread's
1214 // monitors have been transferred to the global in-use list).




1215 
1216 void ObjectSynchronizer::omFlush(Thread * Self) {
1217   ObjectMonitor * list = Self->omFreeList;  // Null-terminated SLL
1218   ObjectMonitor * tail = NULL;
1219   int tally = 0;
1220   if (list != NULL) {
1221     ObjectMonitor * s;
1222     // The thread is going away, the per-thread free monitors
1223     // are freed via set_owner(NULL)
1224     // Link them to tail, which will be linked into the global free list
1225     // gFreeList below, under the gListLock
1226     for (s = list; s != NULL; s = s->FreeNext) {
1227       tally++;
1228       tail = s;
1229       guarantee(s->object() == NULL, "invariant");
1230       guarantee(!s->is_busy(), "invariant");
1231       s->set_owner(NULL);   // redundant but good hygiene
1232     }
1233     guarantee(tail != NULL, "invariant");
1234     assert(Self->omFreeCount == tally, "free-count off");
1235     Self->omFreeList = NULL;
1236     Self->omFreeCount = 0;
1237   }
1238 
1239   ObjectMonitor * inUseList = Self->omInUseList;
1240   ObjectMonitor * inUseTail = NULL;
1241   int inUseTally = 0;
1242   if (inUseList != NULL) {
1243     ObjectMonitor *cur_om;
1244     // The thread is going away, however the omInUseList inflated
1245     // monitors may still be in-use by other threads.
1246     // Link them to inUseTail, which will be linked into the global in-use list
1247     // gOmInUseList below, under the gListLock
1248     for (cur_om = inUseList; cur_om != NULL; cur_om = cur_om->FreeNext) {
1249       inUseTail = cur_om;
1250       inUseTally++;

1251     }
1252     guarantee(inUseTail != NULL, "invariant");
1253     assert(Self->omInUseCount == inUseTally, "in-use count off");
1254     Self->omInUseList = NULL;
1255     Self->omInUseCount = 0;
1256   }
1257 
1258   Thread::muxAcquire(&gListLock, "omFlush");
1259   if (tail != NULL) {
1260     tail->FreeNext = gFreeList;
1261     gFreeList = list;
1262     gMonitorFreeCount += tally;
1263   }
1264 
1265   if (inUseTail != NULL) {
1266     inUseTail->FreeNext = gOmInUseList;
1267     gOmInUseList = inUseList;
1268     gOmInUseCount += inUseTally;
1269   }
1270 
1271   Thread::muxRelease(&gListLock);
1272 
1273   LogStreamHandle(Debug, monitorinflation) lsh_debug;


1281   }
1282   if (ls != NULL) {
1283     ls->print_cr("omFlush: jt=" INTPTR_FORMAT ", free_monitor_tally=%d"
1284                  ", in_use_monitor_tally=%d" ", omFreeProvision=%d",
1285                  p2i(Self), tally, inUseTally, Self->omFreeProvision);
1286   }
1287 }
1288 
1289 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1290                                        const oop obj,
1291                                        ObjectSynchronizer::InflateCause cause) {
1292   assert(event != NULL, "invariant");
1293   assert(event->should_commit(), "invariant");
1294   event->set_monitorClass(obj->klass());
1295   event->set_address((uintptr_t)(void*)obj);
1296   event->set_cause((u1)cause);
1297   event->commit();
1298 }
1299 
1300 // Fast path code shared by multiple functions
1301 void ObjectSynchronizer::inflate_helper(oop obj) {

1302   markOop mark = obj->mark();
1303   if (mark->has_monitor()) {
1304     assert(ObjectSynchronizer::verify_objmon_isinpool(mark->monitor()), "monitor is invalid");
1305     assert(mark->monitor()->header()->is_neutral(), "monitor must record a good object header");










1306     return;
1307   }
1308   inflate(Thread::current(), obj, inflate_cause_vm_internal);
1309 }
1310 
1311 ObjectMonitor* ObjectSynchronizer::inflate(Thread * Self,
1312                                            oop object,
1313                                            const InflateCause cause) {
1314   // Inflate mutates the heap ...
1315   // Relaxing assertion for bug 6320749.
1316   assert(Universe::verify_in_progress() ||
1317          !SafepointSynchronize::is_at_safepoint(), "invariant");
1318 
1319   EventJavaMonitorInflate event;
1320 
1321   for (;;) {
1322     const markOop mark = object->mark();
1323     assert(!mark->has_bias_pattern(), "invariant");
1324 
1325     // The mark can be in one of the following states:
1326     // *  Inflated     - just return
1327     // *  Stack-locked - coerce it to inflated
1328     // *  INFLATING    - busy wait for conversion to complete
1329     // *  Neutral      - aggressively inflate the object.
1330     // *  BIASED       - Illegal.  We should never see this
1331 
1332     // CASE: inflated
1333     if (mark->has_monitor()) {
1334       ObjectMonitor * inf = mark->monitor();





1335       markOop dmw = inf->header();
1336       assert(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1337       assert(oopDesc::equals((oop) inf->object(), object), "invariant");
1338       assert(ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
1339       return inf;
1340     }
1341 
1342     // CASE: inflation in progress - inflating over a stack-lock.
1343     // Some other thread is converting from stack-locked to inflated.
1344     // Only that thread can complete inflation -- other threads must wait.
1345     // The INFLATING value is transient.
1346     // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
1347     // We could always eliminate polling by parking the thread on some auxiliary list.
1348     if (mark == markOopDesc::INFLATING()) {
1349       ReadStableMark(object);
1350       continue;
1351     }
1352 
1353     // CASE: stack-locked
1354     // Could be stack-locked either by this thread or by some other thread.
1355     //
1356     // Note that we allocate the objectmonitor speculatively, _before_ attempting
1357     // to install INFLATING into the mark word.  We originally installed INFLATING,
1358     // allocated the objectmonitor, and then finally STed the address of the
1359     // objectmonitor into the mark.  This was correct, but artificially lengthened
1360     // the interval in which INFLATED appeared in the mark, thus increasing
1361     // the odds of inflation contention.
1362     //
1363     // We now use per-thread private objectmonitor free lists.
1364     // These list are reprovisioned from the global free list outside the
1365     // critical INFLATING...ST interval.  A thread can transfer
1366     // multiple objectmonitors en-mass from the global free list to its local free list.
1367     // This reduces coherency traffic and lock contention on the global free list.
1368     // Using such local free lists, it doesn't matter if the omAlloc() call appears
1369     // before or after the CAS(INFLATING) operation.
1370     // See the comments in omAlloc().
1371 
1372     LogStreamHandle(Trace, monitorinflation) lsh;
1373 
1374     if (mark->has_locker()) {
1375       ObjectMonitor * m = omAlloc(Self);











1376       // Optimistically prepare the objectmonitor - anticipate successful CAS
1377       // We do this before the CAS in order to minimize the length of time
1378       // in which INFLATING appears in the mark.
1379       m->Recycle();
1380       m->_Responsible  = NULL;
1381       m->_recursions   = 0;
1382       m->_SpinDuration = ObjectMonitor::Knob_SpinLimit;   // Consider: maintain by type/class
1383 
1384       markOop cmp = object->cas_set_mark(markOopDesc::INFLATING(), mark);
1385       if (cmp != mark) {
1386         omRelease(Self, m, true);
1387         continue;       // Interference -- just retry
1388       }
1389 
1390       // We've successfully installed INFLATING (0) into the mark-word.
1391       // This is the only case where 0 will appear in a mark-word.
1392       // Only the singular thread that successfully swings the mark-word
1393       // to 0 can perform (or more precisely, complete) inflation.
1394       //
1395       // Why do we CAS a 0 into the mark-word instead of just CASing the


1403       // value from the basiclock on the owner's stack to the objectMonitor, all
1404       // the while preserving the hashCode stability invariants.  If the owner
1405       // decides to release the lock while the value is 0, the unlock will fail
1406       // and control will eventually pass from slow_exit() to inflate.  The owner
1407       // will then spin, waiting for the 0 value to disappear.   Put another way,
1408       // the 0 causes the owner to stall if the owner happens to try to
1409       // drop the lock (restoring the header from the basiclock to the object)
1410       // while inflation is in-progress.  This protocol avoids races that might
1411       // would otherwise permit hashCode values to change or "flicker" for an object.
1412       // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
1413       // 0 serves as a "BUSY" inflate-in-progress indicator.
1414 
1415 
1416       // fetch the displaced mark from the owner's stack.
1417       // The owner can't die or unwind past the lock while our INFLATING
1418       // object is in the mark.  Furthermore the owner can't complete
1419       // an unlock on the object, either.
1420       markOop dmw = mark->displaced_mark_helper();
1421       // Catch if the object's header is not neutral (not locked and
1422       // not marked is what we care about here).
1423       assert(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1424 
1425       // Setup monitor fields to proper values -- prepare the monitor
1426       m->set_header(dmw);
1427 
1428       // Optimization: if the mark->locker stack address is associated
1429       // with this thread we could simply set m->_owner = Self.
1430       // Note that a thread can inflate an object
1431       // that it has stack-locked -- as might happen in wait() -- directly
1432       // with CAS.  That is, we can avoid the xchg-NULL .... ST idiom.
1433       m->set_owner(mark->locker());
1434       m->set_object(object);
1435       // TODO-FIXME: assert BasicLock->dhw != 0.
1436 




1437       // Must preserve store ordering. The monitor state must
1438       // be stable at the time of publishing the monitor address.
1439       guarantee(object->mark() == markOopDesc::INFLATING(), "invariant");
1440       object->release_set_mark(markOopDesc::encode(m));
1441 
1442       // Hopefully the performance counters are allocated on distinct cache lines
1443       // to avoid false sharing on MP systems ...
1444       OM_PERFDATA_OP(Inflations, inc());
1445       if (log_is_enabled(Trace, monitorinflation)) {
1446         ResourceMark rm(Self);
1447         lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark="
1448                      INTPTR_FORMAT ", type='%s'", p2i(object),
1449                      p2i(object->mark()), object->klass()->external_name());
1450       }
1451       if (event.should_commit()) {
1452         post_monitor_inflate_event(&event, object, cause);
1453       }
1454       return m;

1455     }
1456 
1457     // CASE: neutral
1458     // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1459     // If we know we're inflating for entry it's better to inflate by swinging a
1460     // pre-locked objectMonitor pointer into the object header.   A successful
1461     // CAS inflates the object *and* confers ownership to the inflating thread.
1462     // In the current implementation we use a 2-step mechanism where we CAS()
1463     // to inflate and then CAS() again to try to swing _owner from NULL to Self.
1464     // An inflateTry() method that we could call from fast_enter() and slow_enter()
1465     // would be useful.
1466 
1467     // Catch if the object's header is not neutral (not locked and
1468     // not marked is what we care about here).
1469     assert(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark));
1470     ObjectMonitor * m = omAlloc(Self);











1471     // prepare m for installation - set monitor to initial state
1472     m->Recycle();
1473     m->set_header(mark);
1474     m->set_owner(NULL);
1475     m->set_object(object);
1476     m->_recursions   = 0;
1477     m->_Responsible  = NULL;
1478     m->_SpinDuration = ObjectMonitor::Knob_SpinLimit;       // consider: keep metastats by type/class
1479 




1480     if (object->cas_set_mark(markOopDesc::encode(m), mark) != mark) {
1481       m->set_header(NULL);
1482       m->set_object(NULL);
1483       m->Recycle();


1484       omRelease(Self, m, true);
1485       m = NULL;
1486       continue;
1487       // interference - the markword changed - just retry.
1488       // The state-transitions are one-way, so there's no chance of
1489       // live-lock -- "Inflated" is an absorbing state.
1490     }
1491 
1492     // Hopefully the performance counters are allocated on distinct
1493     // cache lines to avoid false sharing on MP systems ...
1494     OM_PERFDATA_OP(Inflations, inc());
1495     if (log_is_enabled(Trace, monitorinflation)) {
1496       ResourceMark rm(Self);
1497       lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark="
1498                    INTPTR_FORMAT ", type='%s'", p2i(object),
1499                    p2i(object->mark()), object->klass()->external_name());
1500     }
1501     if (event.should_commit()) {
1502       post_monitor_inflate_event(&event, object, cause);
1503     }
1504     return m;

1505   }
1506 }
1507 
1508 
1509 // We maintain a list of in-use monitors for each thread.
1510 //
1511 // deflate_thread_local_monitors() scans a single thread's in-use list, while
1512 // deflate_idle_monitors() scans only a global list of in-use monitors which
1513 // is populated only as a thread dies (see omFlush()).
1514 //
1515 // These operations are called at all safepoints, immediately after mutators
1516 // are stopped, but before any objects have moved. Collectively they traverse
1517 // the population of in-use monitors, deflating where possible. The scavenged
1518 // monitors are returned to the global monitor free list.
1519 //
1520 // Beware that we scavenge at *every* stop-the-world point. Having a large
1521 // number of monitors in-use could negatively impact performance. We also want
1522 // to minimize the total # of monitors in circulation, as they incur a small
1523 // footprint penalty.
1524 //
1525 // Perversely, the heap size -- and thus the STW safepoint rate --
1526 // typically drives the scavenge rate.  Large heaps can mean infrequent GC,
1527 // which in turn can mean large(r) numbers of ObjectMonitors in circulation.
1528 // This is an unfortunate aspect of this design.
1529 




















1530 // Deflate a single monitor if not in-use
1531 // Return true if deflated, false if in-use
1532 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
1533                                          ObjectMonitor** freeHeadp,
1534                                          ObjectMonitor** freeTailp) {
1535   bool deflated;
1536   // Normal case ... The monitor is associated with obj.
1537   const markOop mark = obj->mark();
1538   guarantee(mark == markOopDesc::encode(mid), "should match: mark="
1539             INTPTR_FORMAT ", encoded mid=" INTPTR_FORMAT, p2i(mark),
1540             p2i(markOopDesc::encode(mid)));
1541   // Make sure that mark->monitor() and markOopDesc::encode() agree:
1542   guarantee(mark->monitor() == mid, "should match: monitor()=" INTPTR_FORMAT
1543             ", mid=" INTPTR_FORMAT, p2i(mark->monitor()), p2i(mid));
1544   const markOop dmw = mid->header();
1545   guarantee(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1546 
1547   if (mid->is_busy()) {
1548     deflated = false;
1549   } else {
1550     // Deflate the monitor if it is no longer being used
1551     // It's idle - scavenge and return to the global free list
1552     // plain old deflation ...
1553     if (log_is_enabled(Trace, monitorinflation)) {
1554       ResourceMark rm;
1555       log_trace(monitorinflation)("deflate_monitor: "
1556                                   "object=" INTPTR_FORMAT ", mark="
1557                                   INTPTR_FORMAT ", type='%s'", p2i(obj),
1558                                   p2i(mark), obj->klass()->external_name());
1559     }
1560 
1561     // Restore the header back to obj
1562     obj->release_set_mark(dmw);
1563     mid->clear();
1564 
1565     assert(mid->object() == NULL, "invariant: object=" INTPTR_FORMAT,
1566            p2i(mid->object()));

1567 
1568     // Move the object to the working free list defined by freeHeadp, freeTailp
1569     if (*freeHeadp == NULL) *freeHeadp = mid;
1570     if (*freeTailp != NULL) {
1571       ObjectMonitor * prevtail = *freeTailp;
1572       assert(prevtail->FreeNext == NULL, "cleaned up deflated?");
1573       prevtail->FreeNext = mid;
1574     }
1575     *freeTailp = mid;
1576     deflated = true;
1577   }
1578   return deflated;
1579 }
1580 












































































































































1581 // Walk a given monitor list, and deflate idle monitors
1582 // The given list could be a per-thread list or a global list
1583 // Caller acquires gListLock as needed.
1584 //
1585 // In the case of parallel processing of thread local monitor lists,
1586 // work is done by Threads::parallel_threads_do() which ensures that
1587 // each Java thread is processed by exactly one worker thread, and
1588 // thus avoid conflicts that would arise when worker threads would
1589 // process the same monitor lists concurrently.
1590 //
1591 // See also ParallelSPCleanupTask and
1592 // SafepointSynchronize::do_cleanup_tasks() in safepoint.cpp and
1593 // Threads::parallel_java_threads_do() in thread.cpp.
1594 int ObjectSynchronizer::deflate_monitor_list(ObjectMonitor** listHeadp,
1595                                              ObjectMonitor** freeHeadp,
1596                                              ObjectMonitor** freeTailp) {
1597   ObjectMonitor* mid;
1598   ObjectMonitor* next;
1599   ObjectMonitor* cur_mid_in_use = NULL;
1600   int deflated_count = 0;


1604     if (obj != NULL && deflate_monitor(mid, obj, freeHeadp, freeTailp)) {
1605       // if deflate_monitor succeeded,
1606       // extract from per-thread in-use list
1607       if (mid == *listHeadp) {
1608         *listHeadp = mid->FreeNext;
1609       } else if (cur_mid_in_use != NULL) {
1610         cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1611       }
1612       next = mid->FreeNext;
1613       mid->FreeNext = NULL;  // This mid is current tail in the freeHeadp list
1614       mid = next;
1615       deflated_count++;
1616     } else {
1617       cur_mid_in_use = mid;
1618       mid = mid->FreeNext;
1619     }
1620   }
1621   return deflated_count;
1622 }
1623 












































































1624 void ObjectSynchronizer::prepare_deflate_idle_monitors(DeflateMonitorCounters* counters) {
1625   counters->nInuse = 0;              // currently associated with objects
1626   counters->nInCirculation = 0;      // extant
1627   counters->nScavenged = 0;          // reclaimed (global and per-thread)
1628   counters->perThreadScavenged = 0;  // per-thread scavenge total
1629   counters->perThreadTimes = 0.0;    // per-thread scavenge times
1630 }
1631 
1632 void ObjectSynchronizer::deflate_idle_monitors(DeflateMonitorCounters* counters) {
1633   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");









1634   bool deflated = false;
1635 
1636   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged monitors
1637   ObjectMonitor * freeTailp = NULL;
1638   elapsedTimer timer;
1639 
1640   if (log_is_enabled(Info, monitorinflation)) {
1641     timer.start();
1642   }
1643 
1644   // Prevent omFlush from changing mids in Thread dtor's during deflation
1645   // And in case the vm thread is acquiring a lock during a safepoint
1646   // See e.g. 6320749
1647   Thread::muxAcquire(&gListLock, "deflate_idle_monitors");
1648 
1649   // Note: the thread-local monitors lists get deflated in
1650   // a separate pass. See deflate_thread_local_monitors().
1651 
1652   // For moribund threads, scan gOmInUseList
1653   int deflated_count = 0;


1666     // constant-time list splice - prepend scavenged segment to gFreeList
1667     freeTailp->FreeNext = gFreeList;
1668     gFreeList = freeHeadp;
1669   }
1670   Thread::muxRelease(&gListLock);
1671   timer.stop();
1672 
1673   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1674   LogStreamHandle(Info, monitorinflation) lsh_info;
1675   LogStream * ls = NULL;
1676   if (log_is_enabled(Debug, monitorinflation)) {
1677     ls = &lsh_debug;
1678   } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
1679     ls = &lsh_info;
1680   }
1681   if (ls != NULL) {
1682     ls->print_cr("deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count);
1683   }
1684 }
1685 


























































































































1686 void ObjectSynchronizer::finish_deflate_idle_monitors(DeflateMonitorCounters* counters) {
1687   // Report the cumulative time for deflating each thread's idle
1688   // monitors. Note: if the work is split among more than one
1689   // worker thread, then the reported time will likely be more
1690   // than a beginning to end measurement of the phase.


1691   log_info(safepoint, cleanup)("deflating per-thread idle monitors, %3.7f secs, monitors=%d", counters->perThreadTimes, counters->perThreadScavenged);
1692 





1693   gMonitorFreeCount += counters->nScavenged;
1694 




1695   if (log_is_enabled(Debug, monitorinflation)) {
1696     // exit_globals()'s call to audit_and_print_stats() is done
1697     // at the Info level.
1698     ObjectSynchronizer::audit_and_print_stats(false /* on_exit */);
1699   } else if (log_is_enabled(Info, monitorinflation)) {
1700     Thread::muxAcquire(&gListLock, "finish_deflate_idle_monitors");
1701     log_info(monitorinflation)("gMonitorPopulation=%d, gOmInUseCount=%d, "
1702                                "gMonitorFreeCount=%d", gMonitorPopulation,
1703                                gOmInUseCount, gMonitorFreeCount);
1704     Thread::muxRelease(&gListLock);
1705   }
1706 
1707   ForceMonitorScavenge = 0;    // Reset
1708 
1709   OM_PERFDATA_OP(Deflations, inc(counters->nScavenged));
1710   OM_PERFDATA_OP(MonExtant, set_value(counters->nInCirculation));
1711 
1712   GVars.stwRandom = os::random();
1713   GVars.stwCycle++;



1714 }
1715 
1716 void ObjectSynchronizer::deflate_thread_local_monitors(Thread* thread, DeflateMonitorCounters* counters) {
1717   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1718 












1719   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged monitors
1720   ObjectMonitor * freeTailp = NULL;
1721   elapsedTimer timer;
1722 
1723   if (log_is_enabled(Info, safepoint, cleanup) ||
1724       log_is_enabled(Info, monitorinflation)) {
1725     timer.start();
1726   }
1727 
1728   int deflated_count = deflate_monitor_list(thread->omInUseList_addr(), &freeHeadp, &freeTailp);
1729 
1730   Thread::muxAcquire(&gListLock, "deflate_thread_local_monitors");
1731 
1732   // Adjust counters
1733   counters->nInCirculation += thread->omInUseCount;
1734   thread->omInUseCount -= deflated_count;
1735   counters->nScavenged += deflated_count;
1736   counters->nInuse += thread->omInUseCount;
1737   counters->perThreadScavenged += deflated_count;
1738 


1907   } else {
1908     log_error(monitorinflation)("found monitor list errors: error_cnt=%d", error_cnt);
1909   }
1910 
1911   if ((on_exit && log_is_enabled(Info, monitorinflation)) ||
1912       (!on_exit && log_is_enabled(Trace, monitorinflation))) {
1913     // When exiting this log output is at the Info level. When called
1914     // at a safepoint, this log output is at the Trace level since
1915     // there can be a lot of it.
1916     log_in_use_monitor_details(ls, on_exit);
1917   }
1918 
1919   ls->flush();
1920 
1921   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
1922 }
1923 
1924 // Check a free monitor entry; log any errors.
1925 void ObjectSynchronizer::chk_free_entry(JavaThread * jt, ObjectMonitor * n,
1926                                         outputStream * out, int *error_cnt_p) {
1927   if (n->is_busy()) {

1928     if (jt != NULL) {
1929       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
1930                     ": free per-thread monitor must not be busy.", p2i(jt),
1931                     p2i(n));
1932     } else {
1933       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
1934                     "must not be busy.", p2i(n));
1935     }
1936     *error_cnt_p = *error_cnt_p + 1;
1937   }
1938   if (n->header() != NULL) {
1939     if (jt != NULL) {
1940       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
1941                     ": free per-thread monitor must have NULL _header "
1942                     "field: _header=" INTPTR_FORMAT, p2i(jt), p2i(n),
1943                     p2i(n->header()));
1944     } else {

1945       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
1946                     "must have NULL _header field: _header=" INTPTR_FORMAT,
1947                     p2i(n), p2i(n->header()));
1948     }
1949     *error_cnt_p = *error_cnt_p + 1;
1950   }

1951   if (n->object() != NULL) {
1952     if (jt != NULL) {
1953       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
1954                     ": free per-thread monitor must have NULL _object "
1955                     "field: _object=" INTPTR_FORMAT, p2i(jt), p2i(n),
1956                     p2i(n->object()));
1957     } else {
1958       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
1959                     "must have NULL _object field: _object=" INTPTR_FORMAT,
1960                     p2i(n), p2i(n->object()));
1961     }
1962     *error_cnt_p = *error_cnt_p + 1;
1963   }
1964 }
1965 
1966 // Check the global free list and count; log the results of the checks.
1967 void ObjectSynchronizer::chk_global_free_list_and_count(outputStream * out,
1968                                                         int *error_cnt_p) {
1969   int chkMonitorFreeCount = 0;
1970   for (ObjectMonitor * n = gFreeList; n != NULL; n = n->FreeNext) {


2096     out->print_cr("ERROR: jt=" INTPTR_FORMAT ": omInUseCount=%d is not "
2097                   "equal to chkOmInUseCount=%d", p2i(jt), jt->omInUseCount,
2098                   chkOmInUseCount);
2099     *error_cnt_p = *error_cnt_p + 1;
2100   }
2101 }
2102 
2103 // Log details about ObjectMonitors on the in-use lists. The 'BHL'
2104 // flags indicate why the entry is in-use, 'object' and 'object type'
2105 // indicate the associated object and its type.
2106 void ObjectSynchronizer::log_in_use_monitor_details(outputStream * out,
2107                                                     bool on_exit) {
2108   if (!on_exit) {
2109     // Not at VM exit so grab the global list lock.
2110     Thread::muxAcquire(&gListLock, "log_in_use_monitor_details");
2111   }
2112 
2113   if (gOmInUseCount > 0) {
2114     out->print_cr("In-use global monitor info:");
2115     out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2116     out->print_cr("%18s  %s  %18s  %18s",
2117                   "monitor", "BHL", "object", "object type");
2118     out->print_cr("==================  ===  ==================  ==================");
2119     for (ObjectMonitor * n = gOmInUseList; n != NULL; n = n->FreeNext) {
2120       const oop obj = (oop) n->object();
2121       const markOop mark = n->header();
2122       ResourceMark rm;
2123       out->print_cr(INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT "  %s", p2i(n),
2124                     n->is_busy() != 0, mark->hash() != 0, n->owner() != NULL,
2125                     p2i(obj), obj->klass()->external_name());

2126     }
2127   }
2128 
2129   if (!on_exit) {
2130     Thread::muxRelease(&gListLock);
2131   }
2132 
2133   out->print_cr("In-use per-thread monitor info:");
2134   out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2135   out->print_cr("%18s  %18s  %s  %18s  %18s",
2136                 "jt", "monitor", "BHL", "object", "object type");
2137   out->print_cr("==================  ==================  ===  ==================  ==================");
2138   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2139     for (ObjectMonitor * n = jt->omInUseList; n != NULL; n = n->FreeNext) {
2140       const oop obj = (oop) n->object();
2141       const markOop mark = n->header();
2142       ResourceMark rm;
2143       out->print_cr(INTPTR_FORMAT "  " INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT
2144                     "  %s", p2i(jt), p2i(n), n->is_busy() != 0,
2145                     mark->hash() != 0, n->owner() != NULL, p2i(obj),
2146                     obj->klass()->external_name());
2147     }
2148   }
2149 
2150   out->flush();
2151 }
2152 
2153 // Log counts for the global and per-thread monitor lists and return
2154 // the population count.
2155 int ObjectSynchronizer::log_monitor_list_counts(outputStream * out) {
2156   int popCount = 0;
2157   out->print_cr("%18s  %10s  %10s  %10s",
2158                 "Global Lists:", "InUse", "Free", "Total");
2159   out->print_cr("==================  ==========  ==========  ==========");
2160   out->print_cr("%18s  %10d  %10d  %10d", "",
2161                 gOmInUseCount, gMonitorFreeCount, gMonitorPopulation);
2162   popCount += gOmInUseCount + gMonitorFreeCount;
2163 
2164   out->print_cr("%18s  %10s  %10s  %10s",
2165                 "Per-Thread Lists:", "InUse", "Free", "Provision");
2166   out->print_cr("==================  ==========  ==========  ==========");




 107 #endif // ndef DTRACE_ENABLED
 108 
 109 // This exists only as a workaround of dtrace bug 6254741
 110 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
 111   DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
 112   return 0;
 113 }
 114 
 115 #define NINFLATIONLOCKS 256
 116 static volatile intptr_t gInflationLocks[NINFLATIONLOCKS];
 117 
 118 // global list of blocks of monitors
 119 PaddedEnd<ObjectMonitor> * volatile ObjectSynchronizer::gBlockList = NULL;
 120 // global monitor free list
 121 ObjectMonitor * volatile ObjectSynchronizer::gFreeList  = NULL;
 122 // global monitor in-use list, for moribund threads,
 123 // monitors they inflated need to be scanned for deflation
 124 ObjectMonitor * volatile ObjectSynchronizer::gOmInUseList  = NULL;
 125 // count of entries in gOmInUseList
 126 int ObjectSynchronizer::gOmInUseCount = 0;
 127 bool ObjectSynchronizer::_gOmShouldDeflateIdleMonitors = false;
 128 bool volatile ObjectSynchronizer::_is_cleanup_requested = false;
 129 
 130 static volatile intptr_t gListLock = 0;      // protects global monitor lists
 131 static volatile int gMonitorFreeCount  = 0;  // # on gFreeList
 132 static volatile int gMonitorPopulation = 0;  // # Extant -- in circulation
 133 
 134 #define CHAINMARKER (cast_to_oop<intptr_t>(-1))
 135 
 136 
 137 // =====================> Quick functions
 138 
 139 // The quick_* forms are special fast-path variants used to improve
 140 // performance.  In the simplest case, a "quick_*" implementation could
 141 // simply return false, in which case the caller will perform the necessary
 142 // state transitions and call the slow-path form.
 143 // The fast-path is designed to handle frequently arising cases in an efficient
 144 // manner and is just a degenerate "optimistic" variant of the slow-path.
 145 // returns true  -- to indicate the call was satisfied.
 146 // returns false -- to indicate the call needs the services of the slow-path.
 147 // A no-loitering ordinance is in effect for code in the quick_* family
 148 // operators: safepoints or indefinite blocking (blocking that might span a


 195   }
 196 
 197   // biased locking and any other IMS exception states take the slow-path
 198   return false;
 199 }
 200 
 201 
 202 // The LockNode emitted directly at the synchronization site would have
 203 // been too big if it were to have included support for the cases of inflated
 204 // recursive enter and exit, so they go here instead.
 205 // Note that we can't safely call AsyncPrintJavaStack() from within
 206 // quick_enter() as our thread state remains _in_Java.
 207 
 208 bool ObjectSynchronizer::quick_enter(oop obj, Thread * Self,
 209                                      BasicLock * lock) {
 210   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 211   assert(Self->is_Java_thread(), "invariant");
 212   assert(((JavaThread *) Self)->thread_state() == _thread_in_Java, "invariant");
 213   NoSafepointVerifier nsv;
 214   if (obj == NULL) return false;       // Need to throw NPE
 215 
 216   while (true) {
 217     const markOop mark = obj->mark();
 218 
 219     if (mark->has_monitor()) {
 220       ObjectMonitorHandle omh;
 221       if (!omh.save_om_ptr(obj, mark)) {
 222         // Lost a race with async deflation so try again.
 223         assert(AsyncDeflateIdleMonitors, "sanity check");
 224         continue;
 225       }
 226       ObjectMonitor * const m = omh.om_ptr();
 227       assert(oopDesc::equals((oop) m->object(), obj), "invariant");
 228       Thread * const owner = (Thread *) m->_owner;
 229 
 230       // Lock contention and Transactional Lock Elision (TLE) diagnostics
 231       // and observability
 232       // Case: light contention possibly amenable to TLE
 233       // Case: TLE inimical operations such as nested/recursive synchronization
 234 
 235       if (owner == Self) {
 236         m->_recursions++;
 237         return true;
 238       }
 239 
 240       // This Java Monitor is inflated so obj's header will never be
 241       // displaced to this thread's BasicLock. Make the displaced header
 242       // non-NULL so this BasicLock is not seen as recursive nor as
 243       // being locked. We do this unconditionally so that this thread's
 244       // BasicLock cannot be mis-interpreted by any stack walkers. For
 245       // performance reasons, stack walkers generally first check for
 246       // Biased Locking in the object's header, the second check is for
 247       // stack-locking in the object's header, the third check is for
 248       // recursive stack-locking in the displaced header in the BasicLock,
 249       // and last are the inflated Java Monitor (ObjectMonitor) checks.
 250       lock->set_displaced_header(markOopDesc::unused_mark());
 251 
 252       if (owner == NULL && Atomic::replace_if_null(Self, &(m->_owner))) {
 253         assert(m->_recursions == 0, "invariant");
 254         assert(m->_owner == Self, "invariant");
 255         return true;
 256       }
 257     }
 258     break;
 259   }
 260 
 261   // Note that we could inflate in quick_enter.
 262   // This is likely a useful optimization
 263   // Critically, in quick_enter() we must not:
 264   // -- perform bias revocation, or
 265   // -- block indefinitely, or
 266   // -- reach a safepoint
 267 
 268   return false;        // revert to slow-path
 269 }
 270 
 271 // -----------------------------------------------------------------------------
 272 //  Fast Monitor Enter/Exit
 273 // This the fast monitor enter. The interpreter and compiler use
 274 // some assembly copies of this code. Make sure update those code
 275 // if the following function is changed. The implementation is
 276 // extremely sensitive to race condition. Be careful.
 277 
 278 void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock,
 279                                     bool attempt_rebias, TRAPS) {


 322         // does not own the Java Monitor.
 323         ObjectMonitor * m = mark->monitor();
 324         assert(((oop)(m->object()))->mark() == mark, "invariant");
 325         assert(m->is_entered(THREAD), "invariant");
 326       }
 327     }
 328 #endif
 329     return;
 330   }
 331 
 332   if (mark == (markOop) lock) {
 333     // If the object is stack-locked by the current thread, try to
 334     // swing the displaced header from the BasicLock back to the mark.
 335     assert(dhw->is_neutral(), "invariant");
 336     if (object->cas_set_mark(dhw, mark) == mark) {
 337       return;
 338     }
 339   }
 340 
 341   // We have to take the slow-path of possible inflation and then exit.
 342   ObjectMonitorHandle omh;
 343   inflate(&omh, THREAD, object, inflate_cause_vm_internal);
 344   omh.om_ptr()->exit(true, THREAD);
 345 }
 346 
 347 // -----------------------------------------------------------------------------
 348 // Interpreter/Compiler Slow Case
 349 // This routine is used to handle interpreter/compiler slow case
 350 // We don't need to use fast path here, because it must have been
 351 // failed in the interpreter/compiler code.
 352 void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) {
 353   markOop mark = obj->mark();
 354   assert(!mark->has_bias_pattern(), "should not see bias pattern here");
 355 
 356   if (mark->is_neutral()) {
 357     // Anticipate successful CAS -- the ST of the displaced mark must
 358     // be visible <= the ST performed by the CAS.
 359     lock->set_displaced_header(mark);
 360     if (mark == obj()->cas_set_mark((markOop) lock, mark)) {
 361       return;
 362     }
 363     // Fall through to inflate() ...
 364   } else if (mark->has_locker() &&
 365              THREAD->is_lock_owned((address)mark->locker())) {
 366     assert(lock != mark->locker(), "must not re-lock the same lock");
 367     assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock");
 368     lock->set_displaced_header(NULL);
 369     return;
 370   }
 371 
 372   // The object header will never be displaced to this lock,
 373   // so it does not matter what the value is, except that it
 374   // must be non-zero to avoid looking like a re-entrant lock,
 375   // and must not look locked either.
 376   lock->set_displaced_header(markOopDesc::unused_mark());
 377   ObjectMonitorHandle omh;
 378   inflate(&omh, THREAD, obj(), inflate_cause_monitor_enter);
 379   omh.om_ptr()->enter(THREAD);
 380 }
 381 
 382 // This routine is used to handle interpreter/compiler slow case
 383 // We don't need to use fast path here, because it must have
 384 // failed in the interpreter/compiler code. Simply use the heavy
 385 // weight monitor should be ok, unless someone find otherwise.
 386 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
 387   fast_exit(object, lock, THREAD);
 388 }
 389 
 390 // -----------------------------------------------------------------------------
 391 // Class Loader  support to workaround deadlocks on the class loader lock objects
 392 // Also used by GC
 393 // complete_exit()/reenter() are used to wait on a nested lock
 394 // i.e. to give up an outer lock completely and then re-enter
 395 // Used when holding nested locks - lock acquisition order: lock1 then lock2
 396 //  1) complete_exit lock1 - saving recursion count
 397 //  2) wait on lock2
 398 //  3) when notified on lock2, unlock lock2
 399 //  4) reenter lock1 with original recursion count
 400 //  5) lock lock2
 401 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 402 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) {
 403   if (UseBiasedLocking) {
 404     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 405     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 406   }
 407 
 408   ObjectMonitorHandle omh;
 409   inflate(&omh, THREAD, obj(), inflate_cause_vm_internal);
 410   intptr_t ret_code = omh.om_ptr()->complete_exit(THREAD);
 411   return ret_code;
 412 }
 413 
 414 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 415 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) {
 416   if (UseBiasedLocking) {
 417     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 418     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 419   }
 420 
 421   ObjectMonitorHandle omh;
 422   inflate(&omh, THREAD, obj(), inflate_cause_vm_internal);
 423   omh.om_ptr()->reenter(recursion, THREAD);
 424 }
 425 // -----------------------------------------------------------------------------
 426 // JNI locks on java objects
 427 // NOTE: must use heavy weight monitor to handle jni monitor enter
 428 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) {
 429   // the current locking is from JNI instead of Java code
 430   if (UseBiasedLocking) {
 431     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 432     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 433   }
 434   THREAD->set_current_pending_monitor_is_from_java(false);
 435   ObjectMonitorHandle omh;
 436   inflate(&omh, THREAD, obj(), inflate_cause_jni_enter);
 437   omh.om_ptr()->enter(THREAD);
 438   THREAD->set_current_pending_monitor_is_from_java(true);
 439 }
 440 
 441 // NOTE: must use heavy weight monitor to handle jni monitor exit
 442 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
 443   if (UseBiasedLocking) {
 444     Handle h_obj(THREAD, obj);
 445     BiasedLocking::revoke_and_rebias(h_obj, false, THREAD);
 446     obj = h_obj();
 447   }
 448   assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 449 
 450   ObjectMonitorHandle omh;
 451   inflate(&omh, THREAD, obj, inflate_cause_jni_exit);
 452   ObjectMonitor * monitor = omh.om_ptr();
 453   // If this thread has locked the object, exit the monitor.  Note:  can't use
 454   // monitor->check(CHECK); must exit even if an exception is pending.
 455   if (monitor->check(THREAD)) {
 456     monitor->exit(true, THREAD);
 457   }
 458 }
 459 
 460 // -----------------------------------------------------------------------------
 461 // Internal VM locks on java objects
 462 // standard constructor, allows locking failures
 463 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) {
 464   _dolock = doLock;
 465   _thread = thread;
 466   debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);)
 467   _obj = obj;
 468 
 469   if (_dolock) {
 470     ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread);
 471   }
 472 }
 473 
 474 ObjectLocker::~ObjectLocker() {
 475   if (_dolock) {
 476     ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread);
 477   }
 478 }
 479 
 480 
 481 // -----------------------------------------------------------------------------
 482 //  Wait/Notify/NotifyAll
 483 // NOTE: must use heavy weight monitor to handle wait()
 484 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 485   if (UseBiasedLocking) {
 486     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 487     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 488   }
 489   if (millis < 0) {
 490     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 491   }
 492   ObjectMonitorHandle omh;
 493   inflate(&omh, THREAD, obj(), inflate_cause_wait);
 494   ObjectMonitor * monitor = omh.om_ptr();
 495 
 496   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);
 497   monitor->wait(millis, true, THREAD);
 498 
 499   // This dummy call is in place to get around dtrace bug 6254741.  Once
 500   // that's fixed we can uncomment the following line, remove the call
 501   // and change this function back into a "void" func.
 502   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 503   int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
 504   return ret_code;
 505 }
 506 
 507 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) {
 508   if (UseBiasedLocking) {
 509     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 510     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 511   }
 512   if (millis < 0) {
 513     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 514   }
 515   ObjectMonitorHandle omh;
 516   inflate(&omh, THREAD, obj(), inflate_cause_wait);
 517   omh.om_ptr()->wait(millis, false, THREAD);
 518 }
 519 
 520 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 521   if (UseBiasedLocking) {
 522     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 523     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 524   }
 525 
 526   markOop mark = obj->mark();
 527   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
 528     return;
 529   }
 530   ObjectMonitorHandle omh;
 531   inflate(&omh, THREAD, obj(), inflate_cause_notify);
 532   omh.om_ptr()->notify(THREAD);
 533 }
 534 
 535 // NOTE: see comment of notify()
 536 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 537   if (UseBiasedLocking) {
 538     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 539     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 540   }
 541 
 542   markOop mark = obj->mark();
 543   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
 544     return;
 545   }
 546   ObjectMonitorHandle omh;
 547   inflate(&omh, THREAD, obj(), inflate_cause_notify);
 548   omh.om_ptr()->notifyAll(THREAD);
 549 }
 550 
 551 // -----------------------------------------------------------------------------
 552 // Hash Code handling
 553 //
 554 // Performance concern:
 555 // OrderAccess::storestore() calls release() which at one time stored 0
 556 // into the global volatile OrderAccess::dummy variable. This store was
 557 // unnecessary for correctness. Many threads storing into a common location
 558 // causes considerable cache migration or "sloshing" on large SMP systems.
 559 // As such, I avoided using OrderAccess::storestore(). In some cases
 560 // OrderAccess::fence() -- which incurs local latency on the executing
 561 // processor -- is a better choice as it scales on SMP systems.
 562 //
 563 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for
 564 // a discussion of coherency costs. Note that all our current reference
 565 // platforms provide strong ST-ST order, so the issue is moot on IA32,
 566 // x64, and SPARC.
 567 //
 568 // As a general policy we use "volatile" to control compiler-based reordering


 722       Handle hobj(Self, obj);
 723       // Relaxing assertion for bug 6320749.
 724       assert(Universe::verify_in_progress() ||
 725              !SafepointSynchronize::is_at_safepoint(),
 726              "biases should not be seen by VM thread here");
 727       BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
 728       obj = hobj();
 729       assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 730     }
 731   }
 732 
 733   // hashCode() is a heap mutator ...
 734   // Relaxing assertion for bug 6320749.
 735   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
 736          !SafepointSynchronize::is_at_safepoint(), "invariant");
 737   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
 738          Self->is_Java_thread() , "invariant");
 739   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
 740          ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant");
 741 
 742   while (true) {
 743     ObjectMonitor* monitor = NULL;
 744     markOop temp, test;
 745     intptr_t hash;
 746     markOop mark = ReadStableMark(obj);
 747 
 748     // object should remain ineligible for biased locking
 749     assert(!mark->has_bias_pattern(), "invariant");
 750 
 751     if (mark->is_neutral()) {
 752       hash = mark->hash();              // this is a normal header
 753       if (hash != 0) {                  // if it has hash, just return it
 754         return hash;
 755       }
 756       hash = get_next_hash(Self, obj);  // allocate a new hash code
 757       temp = mark->copy_set_hash(hash); // merge the hash code into header
 758       // use (machine word version) atomic operation to install the hash
 759       test = obj->cas_set_mark(temp, mark);
 760       if (test == mark) {
 761         return hash;
 762       }
 763       // If atomic operation failed, we must inflate the header
 764       // into heavy weight monitor. We could add more code here
 765       // for fast path, but it does not worth the complexity.
 766     } else if (mark->has_monitor()) {
 767       ObjectMonitorHandle omh;
 768       if (!omh.save_om_ptr(obj, mark)) {
 769         // Lost a race with async deflation so try again.
 770         assert(AsyncDeflateIdleMonitors, "sanity check");
 771         continue;
 772       }
 773       monitor = omh.om_ptr();
 774       temp = monitor->header();
 775       assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
 776       hash = temp->hash();
 777       if (hash != 0) {
 778         return hash;
 779       }
 780       // Skip to the following code to reduce code size
 781     } else if (Self->is_lock_owned((address)mark->locker())) {
 782       temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
 783       assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
 784       hash = temp->hash();              // by current thread, check if the displaced
 785       if (hash != 0) {                  // header contains hash code
 786         return hash;
 787       }
 788       // WARNING:
 789       // The displaced header in the BasicLock on a thread's stack
 790       // is strictly immutable. It CANNOT be changed in ANY cases.
 791       // So we have to inflate the stack lock into an ObjectMonitor
 792       // even if the current thread owns the lock. The BasicLock on
 793       // a thread's stack can be asynchronously read by other threads
 794       // during an inflate() call so any change to that stack memory
 795       // may not propagate to other threads correctly.
 796     }
 797 
 798     // Inflate the monitor to set hash code
 799     ObjectMonitorHandle omh;
 800     inflate(&omh, Self, obj, inflate_cause_hash_code);
 801     monitor = omh.om_ptr();
 802     // Load displaced header and check it has hash code
 803     mark = monitor->header();
 804     assert(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark));
 805     hash = mark->hash();
 806     if (hash == 0) {
 807       hash = get_next_hash(Self, obj);
 808       temp = mark->copy_set_hash(hash); // merge hash code into header
 809       assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
 810       test = Atomic::cmpxchg(temp, monitor->header_addr(), mark);
 811       if (test != mark) {
 812         // The only non-deflation update to the ObjectMonitor's
 813         // header/dmw field is to merge in the hash code. If someone
 814         // adds a new usage of the header/dmw field, please update
 815         // this code.
 816         // ObjectMonitor::install_displaced_markword_in_object()
 817         // does mark the header/dmw field as part of async deflation,
 818         // but that protocol cannot happen now due to the
 819         // ObjectMonitorHandle above.
 820         hash = test->hash();
 821         assert(test->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(test));
 822         assert(hash != 0, "Trivial unexpected object/monitor header usage.");
 823       }
 824     }
 825     // We finally get the hash
 826     return hash;
 827   }
 828 }
 829 
 830 // Deprecated -- use FastHashCode() instead.
 831 
 832 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
 833   return FastHashCode(Thread::current(), obj());
 834 }
 835 
 836 
 837 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread,
 838                                                    Handle h_obj) {
 839   if (UseBiasedLocking) {
 840     BiasedLocking::revoke_and_rebias(h_obj, false, thread);
 841     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 842   }
 843 
 844   assert(thread == JavaThread::current(), "Can only be called on current thread");
 845   oop obj = h_obj();
 846 
 847   while (true) {
 848     markOop mark = ReadStableMark(obj);
 849 
 850     // Uncontended case, header points to stack
 851     if (mark->has_locker()) {
 852       return thread->is_lock_owned((address)mark->locker());
 853     }
 854     // Contended case, header points to ObjectMonitor (tagged pointer)
 855     if (mark->has_monitor()) {
 856       ObjectMonitorHandle omh;
 857       if (!omh.save_om_ptr(obj, mark)) {
 858         // Lost a race with async deflation so try again.
 859         assert(AsyncDeflateIdleMonitors, "sanity check");
 860         continue;
 861       }
 862       bool ret_code = omh.om_ptr()->is_entered(thread) != 0;
 863       return ret_code;
 864     }
 865     // Unlocked case, header in place
 866     assert(mark->is_neutral(), "sanity check");
 867     return false;
 868   }
 869 }
 870 
 871 // Be aware of this method could revoke bias of the lock object.
 872 // This method queries the ownership of the lock handle specified by 'h_obj'.
 873 // If the current thread owns the lock, it returns owner_self. If no
 874 // thread owns the lock, it returns owner_none. Otherwise, it will return
 875 // owner_other.
 876 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership
 877 (JavaThread *self, Handle h_obj) {
 878   // The caller must beware this method can revoke bias, and
 879   // revocation can result in a safepoint.
 880   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 881   assert(self->thread_state() != _thread_blocked, "invariant");
 882 
 883   // Possible mark states: neutral, biased, stack-locked, inflated
 884 
 885   if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) {
 886     // CASE: biased
 887     BiasedLocking::revoke_and_rebias(h_obj, false, self);
 888     assert(!h_obj->mark()->has_bias_pattern(),
 889            "biases should be revoked by now");
 890   }
 891 
 892   assert(self == JavaThread::current(), "Can only be called on current thread");
 893   oop obj = h_obj();
 894 
 895   while (true) {
 896     markOop mark = ReadStableMark(obj);
 897 
 898     // CASE: stack-locked.  Mark points to a BasicLock on the owner's stack.
 899     if (mark->has_locker()) {
 900       return self->is_lock_owned((address)mark->locker()) ?
 901         owner_self : owner_other;
 902     }
 903 
 904     // CASE: inflated. Mark (tagged pointer) points to an ObjectMonitor.
 905     // The Object:ObjectMonitor relationship is stable as long as we're
 906     // not at a safepoint and AsyncDeflateIdleMonitors is false.
 907     if (mark->has_monitor()) {
 908       ObjectMonitorHandle omh;
 909       if (!omh.save_om_ptr(obj, mark)) {
 910         // Lost a race with async deflation so try again.
 911         assert(AsyncDeflateIdleMonitors, "sanity check");
 912         continue;
 913       }
 914       ObjectMonitor * monitor = omh.om_ptr();
 915       void * owner = monitor->_owner;
 916       if (owner == NULL) return owner_none;
 917       return (owner == self ||
 918               self->is_lock_owned((address)owner)) ? owner_self : owner_other;
 919     }
 920 
 921     // CASE: neutral
 922     assert(mark->is_neutral(), "sanity check");
 923     return owner_none;           // it's unlocked
 924   }
 925 }
 926 
 927 // FIXME: jvmti should call this
 928 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
 929   if (UseBiasedLocking) {
 930     if (SafepointSynchronize::is_at_safepoint()) {
 931       BiasedLocking::revoke_at_safepoint(h_obj);
 932     } else {
 933       BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current());
 934     }
 935     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 936   }
 937 
 938   oop obj = h_obj();

 939 
 940   while (true) {
 941     address owner = NULL;
 942     markOop mark = ReadStableMark(obj);
 943 
 944     // Uncontended case, header points to stack
 945     if (mark->has_locker()) {
 946       owner = (address) mark->locker();
 947     }
 948 
 949     // Contended case, header points to ObjectMonitor (tagged pointer)
 950     else if (mark->has_monitor()) {
 951       ObjectMonitorHandle omh;
 952       if (!omh.save_om_ptr(obj, mark)) {
 953         // Lost a race with async deflation so try again.
 954         assert(AsyncDeflateIdleMonitors, "sanity check");
 955         continue;
 956       }
 957       ObjectMonitor* monitor = omh.om_ptr();
 958       assert(monitor != NULL, "monitor should be non-null");
 959       owner = (address) monitor->owner();
 960     }
 961 
 962     if (owner != NULL) {
 963       // owning_thread_from_monitor_owner() may also return NULL here
 964       return Threads::owning_thread_from_monitor_owner(t_list, owner);
 965     }
 966 
 967     // Unlocked case, header in place
 968     // Cannot have assertion since this object may have been
 969     // locked by another thread when reaching here.
 970     // assert(mark->is_neutral(), "sanity check");
 971 
 972     return NULL;
 973   }
 974 }
 975 
 976 // Visitors ...
 977 
 978 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) {
 979   PaddedEnd<ObjectMonitor> * block = OrderAccess::load_acquire(&gBlockList);
 980   while (block != NULL) {
 981     assert(block->object() == CHAINMARKER, "must be a block header");
 982     for (int i = _BLOCKSIZE - 1; i > 0; i--) {
 983       ObjectMonitor* mid = (ObjectMonitor *)(block + i);
 984       if (mid->is_active()) {
 985         ObjectMonitorHandle omh(mid);
 986 
 987         if (mid->object() == NULL ||
 988             (AsyncDeflateIdleMonitors && mid->_owner == DEFLATER_MARKER)) {
 989           // Only process with closure if the object is set.
 990           // For async deflation, race here if monitor is not owned!
 991           // The above ref_count bump (in ObjectMonitorHandle ctr)
 992           // will cause subsequent async deflation to skip it.
 993           // However, previous or concurrent async deflation is a race.
 994           continue;
 995         }
 996         closure->do_monitor(mid);
 997       }
 998     }
 999     block = (PaddedEnd<ObjectMonitor> *)block->FreeNext;
1000   }
1001 }
1002 
1003 // Get the next block in the block list.
1004 static inline PaddedEnd<ObjectMonitor>* next(PaddedEnd<ObjectMonitor>* block) {
1005   assert(block->object() == CHAINMARKER, "must be a block header");
1006   block = (PaddedEnd<ObjectMonitor>*) block->FreeNext;
1007   assert(block == NULL || block->object() == CHAINMARKER, "must be a block header");
1008   return block;
1009 }
1010 
1011 static bool monitors_used_above_threshold() {
1012   if (gMonitorPopulation == 0) {
1013     return false;
1014   }
1015   int monitors_used = gMonitorPopulation - gMonitorFreeCount;


1086 // See also: GuaranteedSafepointInterval
1087 //
1088 // The current implementation uses asynchronous VM operations.
1089 
1090 static void InduceScavenge(Thread * Self, const char * Whence) {
1091   // Induce STW safepoint to trim monitors
1092   // Ultimately, this results in a call to deflate_idle_monitors() in the near future.
1093   // More precisely, trigger an asynchronous STW safepoint as the number
1094   // of active monitors passes the specified threshold.
1095   // TODO: assert thread state is reasonable
1096 
1097   if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) {
1098     // Induce a 'null' safepoint to scavenge monitors
1099     // Must VM_Operation instance be heap allocated as the op will be enqueue and posted
1100     // to the VMthread and have a lifespan longer than that of this activation record.
1101     // The VMThread will delete the op when completed.
1102     VMThread::execute(new VM_ScavengeMonitors());
1103   }
1104 }
1105 
1106 ObjectMonitor* ObjectSynchronizer::omAlloc(Thread * Self,
1107                                            const InflateCause cause) {
1108   // A large MAXPRIVATE value reduces both list lock contention
1109   // and list coherency traffic, but also tends to increase the
1110   // number of objectMonitors in circulation as well as the STW
1111   // scavenge costs.  As usual, we lean toward time in space-time
1112   // tradeoffs.
1113   const int MAXPRIVATE = 1024;
1114 
1115   if (AsyncDeflateIdleMonitors) {
1116     JavaThread * jt = (JavaThread *)Self;
1117     if (jt->omShouldDeflateIdleMonitors && jt->omInUseCount > 0 &&
1118         cause != inflate_cause_vm_internal) {
1119       // Deflate any per-thread idle monitors for this JavaThread if
1120       // this is not an internal inflation. Clean up your own mess.
1121       // (Gibbs Rule 45) Otherwise, skip this cleanup.
1122       // deflate_global_idle_monitors_using_JT() is called by the ServiceThread.
1123       debug_only(jt->check_for_valid_safepoint_state(false);)
1124       ObjectSynchronizer::deflate_per_thread_idle_monitors_using_JT();
1125     }
1126   }
1127 
1128   for (;;) {
1129     ObjectMonitor * m;
1130 
1131     // 1: try to allocate from the thread's local omFreeList.
1132     // Threads will attempt to allocate first from their local list, then
1133     // from the global list, and only after those attempts fail will the thread
1134     // attempt to instantiate new monitors.   Thread-local free lists take
1135     // heat off the gListLock and improve allocation latency, as well as reducing
1136     // coherency traffic on the shared global list.
1137     m = Self->omFreeList;
1138     if (m != NULL) {
1139       Self->omFreeList = m->FreeNext;
1140       Self->omFreeCount--;
1141       guarantee(m->object() == NULL, "invariant");
1142       m->set_allocation_state(ObjectMonitor::New);
1143       m->FreeNext = Self->omInUseList;
1144       Self->omInUseList = m;
1145       Self->omInUseCount++;
1146       return m;
1147     }
1148 
1149     // 2: try to allocate from the global gFreeList
1150     // CONSIDER: use muxTry() instead of muxAcquire().
1151     // If the muxTry() fails then drop immediately into case 3.
1152     // If we're using thread-local free lists then try
1153     // to reprovision the caller's free list.
1154     if (gFreeList != NULL) {
1155       // Reprovision the thread's omFreeList.
1156       // Use bulk transfers to reduce the allocation rate and heat
1157       // on various locks.
1158       Thread::muxAcquire(&gListLock, "omAlloc(1)");
1159       for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL;) {
1160         gMonitorFreeCount--;
1161         ObjectMonitor * take = gFreeList;
1162         gFreeList = take->FreeNext;
1163         guarantee(take->object() == NULL, "invariant");
1164         if (AsyncDeflateIdleMonitors) {
1165           // Clear any values we allowed to linger during async deflation.
1166           take->_header = NULL;
1167           take->set_owner(NULL);
1168 
1169           if (take->ref_count() < 0) {
1170             // Add back max_jint to restore the ref_count field to its
1171             // proper value.
1172             Atomic::add(max_jint, &take->_ref_count);
1173 
1174             assert(take->ref_count() >= 0, "must not be negative: ref_count=%d",
1175                    take->ref_count());
1176           }
1177         }
1178         guarantee(!take->is_busy(), "invariant");
1179         take->Recycle();
1180         assert(take->is_free(), "invariant");
1181         omRelease(Self, take, false);
1182       }
1183       Thread::muxRelease(&gListLock);
1184       Self->omFreeProvision += 1 + (Self->omFreeProvision/2);
1185       if (Self->omFreeProvision > MAXPRIVATE) Self->omFreeProvision = MAXPRIVATE;
1186 
1187       const int mx = MonitorBound;
1188       if (mx > 0 && (gMonitorPopulation-gMonitorFreeCount) > mx) {
1189         // We can't safely induce a STW safepoint from omAlloc() as our thread
1190         // state may not be appropriate for such activities and callers may hold
1191         // naked oops, so instead we defer the action.
1192         InduceScavenge(Self, "omAlloc");
1193       }
1194       continue;
1195     }
1196 
1197     // 3: allocate a block of new ObjectMonitors
1198     // Both the local and global free lists are empty -- resort to malloc().
1199     // In the current implementation objectMonitors are TSM - immortal.
1200     // Ideally, we'd write "new ObjectMonitor[_BLOCKSIZE], but we want


1213 
1214     // NOTE: (almost) no way to recover if allocation failed.
1215     // We might be able to induce a STW safepoint and scavenge enough
1216     // objectMonitors to permit progress.
1217     if (temp == NULL) {
1218       vm_exit_out_of_memory(neededsize, OOM_MALLOC_ERROR,
1219                             "Allocate ObjectMonitors");
1220     }
1221     (void)memset((void *) temp, 0, neededsize);
1222 
1223     // Format the block.
1224     // initialize the linked list, each monitor points to its next
1225     // forming the single linked free list, the very first monitor
1226     // will points to next block, which forms the block list.
1227     // The trick of using the 1st element in the block as gBlockList
1228     // linkage should be reconsidered.  A better implementation would
1229     // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; }
1230 
1231     for (int i = 1; i < _BLOCKSIZE; i++) {
1232       temp[i].FreeNext = (ObjectMonitor *)&temp[i+1];
1233       assert(temp[i].is_free(), "invariant");
1234     }
1235 
1236     // terminate the last monitor as the end of list
1237     temp[_BLOCKSIZE - 1].FreeNext = NULL;
1238 
1239     // Element [0] is reserved for global list linkage
1240     temp[0].set_object(CHAINMARKER);
1241 
1242     // Consider carving out this thread's current request from the
1243     // block in hand.  This avoids some lock traffic and redundant
1244     // list activity.
1245 
1246     // Acquire the gListLock to manipulate gBlockList and gFreeList.
1247     // An Oyama-Taura-Yonezawa scheme might be more efficient.
1248     Thread::muxAcquire(&gListLock, "omAlloc(2)");
1249     gMonitorPopulation += _BLOCKSIZE-1;
1250     gMonitorFreeCount += _BLOCKSIZE-1;
1251 
1252     // Add the new block to the list of extant blocks (gBlockList).
1253     // The very first objectMonitor in a block is reserved and dedicated.


1256     // There are lock-free uses of gBlockList so make sure that
1257     // the previous stores happen before we update gBlockList.
1258     OrderAccess::release_store(&gBlockList, temp);
1259 
1260     // Add the new string of objectMonitors to the global free list
1261     temp[_BLOCKSIZE - 1].FreeNext = gFreeList;
1262     gFreeList = temp + 1;
1263     Thread::muxRelease(&gListLock);
1264   }
1265 }
1266 
1267 // Place "m" on the caller's private per-thread omFreeList.
1268 // In practice there's no need to clamp or limit the number of
1269 // monitors on a thread's omFreeList as the only time we'll call
1270 // omRelease is to return a monitor to the free list after a CAS
1271 // attempt failed.  This doesn't allow unbounded #s of monitors to
1272 // accumulate on a thread's free list.
1273 //
1274 // Key constraint: all ObjectMonitors on a thread's free list and the global
1275 // free list must have their object field set to null. This prevents the
1276 // scavenger -- deflate_monitor_list() or deflate_monitor_list_using_JT()
1277 // -- from reclaiming them while we are trying to release them.
1278 
1279 void ObjectSynchronizer::omRelease(Thread * Self, ObjectMonitor * m,
1280                                    bool fromPerThreadAlloc) {
1281   guarantee(m->header() == NULL, "invariant");
1282   guarantee(m->object() == NULL, "invariant");
1283   guarantee(((m->is_busy()|m->_recursions) == 0), "freeing in-use monitor");
1284   m->set_allocation_state(ObjectMonitor::Free);
1285   // Remove from omInUseList
1286   if (fromPerThreadAlloc) {
1287     ObjectMonitor* cur_mid_in_use = NULL;
1288     bool extracted = false;
1289     for (ObjectMonitor* mid = Self->omInUseList; mid != NULL; cur_mid_in_use = mid, mid = mid->FreeNext) {
1290       if (m == mid) {
1291         // extract from per-thread in-use list
1292         if (mid == Self->omInUseList) {
1293           Self->omInUseList = mid->FreeNext;
1294         } else if (cur_mid_in_use != NULL) {
1295           cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1296         }
1297         extracted = true;
1298         Self->omInUseCount--;
1299         break;
1300       }
1301     }
1302     assert(extracted, "Should have extracted from in-use list");
1303   }
1304 
1305   // FreeNext is used for both omInUseList and omFreeList, so clear old before setting new
1306   m->FreeNext = Self->omFreeList;
1307   guarantee(m->is_free(), "invariant");
1308   Self->omFreeList = m;
1309   Self->omFreeCount++;
1310 }
1311 
1312 // Return the monitors of a moribund thread's local free list to
1313 // the global free list.  Typically a thread calls omFlush() when
1314 // it's dying.  We could also consider having the VM thread steal
1315 // monitors from threads that have not run java code over a few
1316 // consecutive STW safepoints.  Relatedly, we might decay
1317 // omFreeProvision at STW safepoints.
1318 //
1319 // Also return the monitors of a moribund thread's omInUseList to
1320 // a global gOmInUseList under the global list lock so these
1321 // will continue to be scanned.
1322 //
1323 // We currently call omFlush() from Threads::remove() _before the thread
1324 // has been excised from the thread list and is no longer a mutator.
1325 // This means that omFlush() cannot run concurrently with a safepoint and
1326 // interleave with the deflate_idle_monitors scavenge operator. In particular,
1327 // this ensures that the thread's monitors are scanned by a GC safepoint,
1328 // either via Thread::oops_do() (if safepoint happens before omFlush()) or via
1329 // ObjectSynchronizer::oops_do() (if it happens after omFlush() and the thread's
1330 // monitors have been transferred to the global in-use list).
1331 //
1332 // With AsyncDeflateIdleMonitors, deflate_global_idle_monitors_using_JT()
1333 // and deflate_per_thread_idle_monitors_using_JT() (in another thread) can
1334 // run at the same time as omFlush() so we have to be careful.
1335 
1336 void ObjectSynchronizer::omFlush(Thread * Self) {
1337   ObjectMonitor * list = Self->omFreeList;  // Null-terminated SLL
1338   ObjectMonitor * tail = NULL;
1339   int tally = 0;
1340   if (list != NULL) {
1341     ObjectMonitor * s;
1342     // The thread is going away, the per-thread free monitors
1343     // are freed via set_owner(NULL)
1344     // Link them to tail, which will be linked into the global free list
1345     // gFreeList below, under the gListLock
1346     for (s = list; s != NULL; s = s->FreeNext) {
1347       tally++;
1348       tail = s;
1349       guarantee(s->object() == NULL, "invariant");
1350       guarantee(!s->is_busy(), "invariant");
1351       s->set_owner(NULL);   // redundant but good hygiene
1352     }
1353     guarantee(tail != NULL, "invariant");
1354     ADIM_guarantee(Self->omFreeCount == tally, "free-count off");
1355     Self->omFreeList = NULL;
1356     Self->omFreeCount = 0;
1357   }
1358 
1359   ObjectMonitor * inUseList = Self->omInUseList;
1360   ObjectMonitor * inUseTail = NULL;
1361   int inUseTally = 0;
1362   if (inUseList != NULL) {
1363     ObjectMonitor *cur_om;
1364     // The thread is going away, however the omInUseList inflated
1365     // monitors may still be in-use by other threads.
1366     // Link them to inUseTail, which will be linked into the global in-use list
1367     // gOmInUseList below, under the gListLock
1368     for (cur_om = inUseList; cur_om != NULL; cur_om = cur_om->FreeNext) {
1369       inUseTail = cur_om;
1370       inUseTally++;
1371       ADIM_guarantee(cur_om->is_active(), "invariant");
1372     }
1373     guarantee(inUseTail != NULL, "invariant");
1374     ADIM_guarantee(Self->omInUseCount == inUseTally, "in-use count off");
1375     Self->omInUseList = NULL;
1376     Self->omInUseCount = 0;
1377   }
1378 
1379   Thread::muxAcquire(&gListLock, "omFlush");
1380   if (tail != NULL) {
1381     tail->FreeNext = gFreeList;
1382     gFreeList = list;
1383     gMonitorFreeCount += tally;
1384   }
1385 
1386   if (inUseTail != NULL) {
1387     inUseTail->FreeNext = gOmInUseList;
1388     gOmInUseList = inUseList;
1389     gOmInUseCount += inUseTally;
1390   }
1391 
1392   Thread::muxRelease(&gListLock);
1393 
1394   LogStreamHandle(Debug, monitorinflation) lsh_debug;


1402   }
1403   if (ls != NULL) {
1404     ls->print_cr("omFlush: jt=" INTPTR_FORMAT ", free_monitor_tally=%d"
1405                  ", in_use_monitor_tally=%d" ", omFreeProvision=%d",
1406                  p2i(Self), tally, inUseTally, Self->omFreeProvision);
1407   }
1408 }
1409 
1410 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1411                                        const oop obj,
1412                                        ObjectSynchronizer::InflateCause cause) {
1413   assert(event != NULL, "invariant");
1414   assert(event->should_commit(), "invariant");
1415   event->set_monitorClass(obj->klass());
1416   event->set_address((uintptr_t)(void*)obj);
1417   event->set_cause((u1)cause);
1418   event->commit();
1419 }
1420 
1421 // Fast path code shared by multiple functions
1422 void ObjectSynchronizer::inflate_helper(ObjectMonitorHandle * omh_p, oop obj) {
1423   while (true) {
1424     markOop mark = obj->mark();
1425     if (mark->has_monitor()) {
1426       if (!omh_p->save_om_ptr(obj, mark)) {
1427         // Lost a race with async deflation so try again.
1428         assert(AsyncDeflateIdleMonitors, "sanity check");
1429         continue;
1430       }
1431       ObjectMonitor * monitor = omh_p->om_ptr();
1432       assert(ObjectSynchronizer::verify_objmon_isinpool(monitor), "monitor is invalid");
1433       markOop dmw = monitor->header();
1434       assert(dmw->is_neutral(), "sanity check: header=" INTPTR_FORMAT, p2i(dmw));
1435       return;
1436     }
1437     inflate(omh_p, Thread::current(), obj, inflate_cause_vm_internal);
1438     return;
1439   }

1440 }
1441 
1442 void ObjectSynchronizer::inflate(ObjectMonitorHandle * omh_p, Thread * Self,
1443                                  oop object, const InflateCause cause) {

1444   // Inflate mutates the heap ...
1445   // Relaxing assertion for bug 6320749.
1446   assert(Universe::verify_in_progress() ||
1447          !SafepointSynchronize::is_at_safepoint(), "invariant");
1448 
1449   EventJavaMonitorInflate event;
1450 
1451   for (;;) {
1452     const markOop mark = object->mark();
1453     assert(!mark->has_bias_pattern(), "invariant");
1454 
1455     // The mark can be in one of the following states:
1456     // *  Inflated     - just return
1457     // *  Stack-locked - coerce it to inflated
1458     // *  INFLATING    - busy wait for conversion to complete
1459     // *  Neutral      - aggressively inflate the object.
1460     // *  BIASED       - Illegal.  We should never see this
1461 
1462     // CASE: inflated
1463     if (mark->has_monitor()) {
1464       if (!omh_p->save_om_ptr(object, mark)) {
1465         // Lost a race with async deflation so try again.
1466         assert(AsyncDeflateIdleMonitors, "sanity check");
1467         continue;
1468       }
1469       ObjectMonitor * inf = omh_p->om_ptr();
1470       markOop dmw = inf->header();
1471       assert(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1472       assert(oopDesc::equals((oop) inf->object(), object), "invariant");
1473       assert(ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
1474       return;
1475     }
1476 
1477     // CASE: inflation in progress - inflating over a stack-lock.
1478     // Some other thread is converting from stack-locked to inflated.
1479     // Only that thread can complete inflation -- other threads must wait.
1480     // The INFLATING value is transient.
1481     // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
1482     // We could always eliminate polling by parking the thread on some auxiliary list.
1483     if (mark == markOopDesc::INFLATING()) {
1484       ReadStableMark(object);
1485       continue;
1486     }
1487 
1488     // CASE: stack-locked
1489     // Could be stack-locked either by this thread or by some other thread.
1490     //
1491     // Note that we allocate the objectmonitor speculatively, _before_ attempting
1492     // to install INFLATING into the mark word.  We originally installed INFLATING,
1493     // allocated the objectmonitor, and then finally STed the address of the
1494     // objectmonitor into the mark.  This was correct, but artificially lengthened
1495     // the interval in which INFLATED appeared in the mark, thus increasing
1496     // the odds of inflation contention.
1497     //
1498     // We now use per-thread private objectmonitor free lists.
1499     // These list are reprovisioned from the global free list outside the
1500     // critical INFLATING...ST interval.  A thread can transfer
1501     // multiple objectmonitors en-mass from the global free list to its local free list.
1502     // This reduces coherency traffic and lock contention on the global free list.
1503     // Using such local free lists, it doesn't matter if the omAlloc() call appears
1504     // before or after the CAS(INFLATING) operation.
1505     // See the comments in omAlloc().
1506 
1507     LogStreamHandle(Trace, monitorinflation) lsh;
1508 
1509     if (mark->has_locker()) {
1510       ObjectMonitor * m;
1511       if (!AsyncDeflateIdleMonitors || cause == inflate_cause_vm_internal) {
1512         // If !AsyncDeflateIdleMonitors or if an internal inflation, then
1513         // we won't stop for a potential safepoint in omAlloc.
1514         m = omAlloc(Self, cause);
1515       } else {
1516         // If AsyncDeflateIdleMonitors and not an internal inflation, then
1517         // we may stop for a safepoint in omAlloc() so protect object.
1518         Handle h_obj(Self, object);
1519         m = omAlloc(Self, cause);
1520         object = h_obj();  // Refresh object.
1521       }
1522       // Optimistically prepare the objectmonitor - anticipate successful CAS
1523       // We do this before the CAS in order to minimize the length of time
1524       // in which INFLATING appears in the mark.
1525       m->Recycle();
1526       m->_Responsible  = NULL;
1527       m->_recursions   = 0;
1528       m->_SpinDuration = ObjectMonitor::Knob_SpinLimit;   // Consider: maintain by type/class
1529 
1530       markOop cmp = object->cas_set_mark(markOopDesc::INFLATING(), mark);
1531       if (cmp != mark) {
1532         omRelease(Self, m, true);
1533         continue;       // Interference -- just retry
1534       }
1535 
1536       // We've successfully installed INFLATING (0) into the mark-word.
1537       // This is the only case where 0 will appear in a mark-word.
1538       // Only the singular thread that successfully swings the mark-word
1539       // to 0 can perform (or more precisely, complete) inflation.
1540       //
1541       // Why do we CAS a 0 into the mark-word instead of just CASing the


1549       // value from the basiclock on the owner's stack to the objectMonitor, all
1550       // the while preserving the hashCode stability invariants.  If the owner
1551       // decides to release the lock while the value is 0, the unlock will fail
1552       // and control will eventually pass from slow_exit() to inflate.  The owner
1553       // will then spin, waiting for the 0 value to disappear.   Put another way,
1554       // the 0 causes the owner to stall if the owner happens to try to
1555       // drop the lock (restoring the header from the basiclock to the object)
1556       // while inflation is in-progress.  This protocol avoids races that might
1557       // would otherwise permit hashCode values to change or "flicker" for an object.
1558       // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
1559       // 0 serves as a "BUSY" inflate-in-progress indicator.
1560 
1561 
1562       // fetch the displaced mark from the owner's stack.
1563       // The owner can't die or unwind past the lock while our INFLATING
1564       // object is in the mark.  Furthermore the owner can't complete
1565       // an unlock on the object, either.
1566       markOop dmw = mark->displaced_mark_helper();
1567       // Catch if the object's header is not neutral (not locked and
1568       // not marked is what we care about here).
1569       ADIM_guarantee(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1570 
1571       // Setup monitor fields to proper values -- prepare the monitor
1572       m->set_header(dmw);
1573 
1574       // Optimization: if the mark->locker stack address is associated
1575       // with this thread we could simply set m->_owner = Self.
1576       // Note that a thread can inflate an object
1577       // that it has stack-locked -- as might happen in wait() -- directly
1578       // with CAS.  That is, we can avoid the xchg-NULL .... ST idiom.
1579       m->set_owner(mark->locker());
1580       m->set_object(object);
1581       // TODO-FIXME: assert BasicLock->dhw != 0.
1582 
1583       omh_p->set_om_ptr(m);
1584       assert(m->is_new(), "freshly allocated monitor must be new");
1585       m->set_allocation_state(ObjectMonitor::Old);
1586 
1587       // Must preserve store ordering. The monitor state must
1588       // be stable at the time of publishing the monitor address.
1589       guarantee(object->mark() == markOopDesc::INFLATING(), "invariant");
1590       object->release_set_mark(markOopDesc::encode(m));
1591 
1592       // Hopefully the performance counters are allocated on distinct cache lines
1593       // to avoid false sharing on MP systems ...
1594       OM_PERFDATA_OP(Inflations, inc());
1595       if (log_is_enabled(Trace, monitorinflation)) {
1596         ResourceMark rm(Self);
1597         lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark="
1598                      INTPTR_FORMAT ", type='%s'", p2i(object),
1599                      p2i(object->mark()), object->klass()->external_name());
1600       }
1601       if (event.should_commit()) {
1602         post_monitor_inflate_event(&event, object, cause);
1603       }
1604       ADIM_guarantee(!m->is_free(), "inflated monitor to be returned cannot be free");
1605       return;
1606     }
1607 
1608     // CASE: neutral
1609     // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1610     // If we know we're inflating for entry it's better to inflate by swinging a
1611     // pre-locked objectMonitor pointer into the object header.   A successful
1612     // CAS inflates the object *and* confers ownership to the inflating thread.
1613     // In the current implementation we use a 2-step mechanism where we CAS()
1614     // to inflate and then CAS() again to try to swing _owner from NULL to Self.
1615     // An inflateTry() method that we could call from fast_enter() and slow_enter()
1616     // would be useful.
1617 
1618     // Catch if the object's header is not neutral (not locked and
1619     // not marked is what we care about here).
1620     ADIM_guarantee(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark));
1621     ObjectMonitor * m;
1622     if (!AsyncDeflateIdleMonitors || cause == inflate_cause_vm_internal) {
1623       // If !AsyncDeflateIdleMonitors or if an internal inflation, then
1624       // we won't stop for a potential safepoint in omAlloc.
1625       m = omAlloc(Self, cause);
1626     } else {
1627       // If AsyncDeflateIdleMonitors and not an internal inflation, then
1628       // we may stop for a safepoint in omAlloc() so protect object.
1629       Handle h_obj(Self, object);
1630       m = omAlloc(Self, cause);
1631       object = h_obj();  // Refresh object.
1632     }
1633     // prepare m for installation - set monitor to initial state
1634     m->Recycle();
1635     m->set_header(mark);
1636     m->set_owner(NULL);
1637     m->set_object(object);
1638     m->_recursions   = 0;
1639     m->_Responsible  = NULL;
1640     m->_SpinDuration = ObjectMonitor::Knob_SpinLimit;       // consider: keep metastats by type/class
1641 
1642     omh_p->set_om_ptr(m);
1643     assert(m->is_new(), "freshly allocated monitor must be new");
1644     m->set_allocation_state(ObjectMonitor::Old);
1645 
1646     if (object->cas_set_mark(markOopDesc::encode(m), mark) != mark) {
1647       m->set_header(NULL);
1648       m->set_object(NULL);
1649       m->Recycle();
1650       omh_p->set_om_ptr(NULL);
1651       // omRelease() will reset the allocation state
1652       omRelease(Self, m, true);
1653       m = NULL;
1654       continue;
1655       // interference - the markword changed - just retry.
1656       // The state-transitions are one-way, so there's no chance of
1657       // live-lock -- "Inflated" is an absorbing state.
1658     }
1659 
1660     // Hopefully the performance counters are allocated on distinct
1661     // cache lines to avoid false sharing on MP systems ...
1662     OM_PERFDATA_OP(Inflations, inc());
1663     if (log_is_enabled(Trace, monitorinflation)) {
1664       ResourceMark rm(Self);
1665       lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark="
1666                    INTPTR_FORMAT ", type='%s'", p2i(object),
1667                    p2i(object->mark()), object->klass()->external_name());
1668     }
1669     if (event.should_commit()) {
1670       post_monitor_inflate_event(&event, object, cause);
1671     }
1672     ADIM_guarantee(!m->is_free(), "inflated monitor to be returned cannot be free");
1673     return;
1674   }
1675 }
1676 
1677 
1678 // We maintain a list of in-use monitors for each thread.
1679 //
1680 // deflate_thread_local_monitors() scans a single thread's in-use list, while
1681 // deflate_idle_monitors() scans only a global list of in-use monitors which
1682 // is populated only as a thread dies (see omFlush()).
1683 //
1684 // These operations are called at all safepoints, immediately after mutators
1685 // are stopped, but before any objects have moved. Collectively they traverse
1686 // the population of in-use monitors, deflating where possible. The scavenged
1687 // monitors are returned to the global monitor free list.
1688 //
1689 // Beware that we scavenge at *every* stop-the-world point. Having a large
1690 // number of monitors in-use could negatively impact performance. We also want
1691 // to minimize the total # of monitors in circulation, as they incur a small
1692 // footprint penalty.
1693 //
1694 // Perversely, the heap size -- and thus the STW safepoint rate --
1695 // typically drives the scavenge rate.  Large heaps can mean infrequent GC,
1696 // which in turn can mean large(r) numbers of ObjectMonitors in circulation.
1697 // This is an unfortunate aspect of this design.
1698 
1699 void ObjectSynchronizer::do_safepoint_work(DeflateMonitorCounters* _counters) {
1700   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1701 
1702   // The per-thread in-use lists are handled in
1703   // ParallelSPCleanupThreadClosure::do_thread().
1704 
1705   if (!AsyncDeflateIdleMonitors || is_cleanup_requested()) {
1706     // Use the older mechanism for the global in-use list or
1707     // if a special cleanup has been requested.
1708     ObjectSynchronizer::deflate_idle_monitors(_counters);
1709     return;
1710   }
1711 
1712   log_debug(monitorinflation)("requesting deflation of idle monitors.");
1713   // Request deflation of global idle monitors by the ServiceThread:
1714   _gOmShouldDeflateIdleMonitors = true;
1715   MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1716   Service_lock->notify_all();
1717 }
1718 
1719 // Deflate a single monitor if not in-use
1720 // Return true if deflated, false if in-use
1721 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
1722                                          ObjectMonitor** freeHeadp,
1723                                          ObjectMonitor** freeTailp) {
1724   bool deflated;
1725   // Normal case ... The monitor is associated with obj.
1726   const markOop mark = obj->mark();
1727   guarantee(mark == markOopDesc::encode(mid), "should match: mark="
1728             INTPTR_FORMAT ", encoded mid=" INTPTR_FORMAT, p2i(mark),
1729             p2i(markOopDesc::encode(mid)));
1730   // Make sure that mark->monitor() and markOopDesc::encode() agree:
1731   guarantee(mark->monitor() == mid, "should match: monitor()=" INTPTR_FORMAT
1732             ", mid=" INTPTR_FORMAT, p2i(mark->monitor()), p2i(mid));
1733   const markOop dmw = mid->header();
1734   guarantee(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1735 
1736   if (mid->is_busy()) {
1737     deflated = false;
1738   } else {
1739     // Deflate the monitor if it is no longer being used
1740     // It's idle - scavenge and return to the global free list
1741     // plain old deflation ...
1742     if (log_is_enabled(Trace, monitorinflation)) {
1743       ResourceMark rm;
1744       log_trace(monitorinflation)("deflate_monitor: "
1745                                   "object=" INTPTR_FORMAT ", mark="
1746                                   INTPTR_FORMAT ", type='%s'", p2i(obj),
1747                                   p2i(mark), obj->klass()->external_name());
1748     }
1749 
1750     // Restore the header back to obj
1751     obj->release_set_mark(dmw);
1752     mid->clear();
1753 
1754     assert(mid->object() == NULL, "invariant: object=" INTPTR_FORMAT,
1755            p2i(mid->object()));
1756     assert(mid->is_free(), "invariant");
1757 
1758     // Move the object to the working free list defined by freeHeadp, freeTailp
1759     if (*freeHeadp == NULL) *freeHeadp = mid;
1760     if (*freeTailp != NULL) {
1761       ObjectMonitor * prevtail = *freeTailp;
1762       assert(prevtail->FreeNext == NULL, "cleaned up deflated?");
1763       prevtail->FreeNext = mid;
1764     }
1765     *freeTailp = mid;
1766     deflated = true;
1767   }
1768   return deflated;
1769 }
1770 
1771 // Deflate the specified ObjectMonitor if not in-use using a JavaThread.
1772 // Returns true if it was deflated and false otherwise.
1773 //
1774 // The async deflation protocol sets owner to DEFLATER_MARKER and
1775 // makes ref_count negative as signals to contending threads that
1776 // an async deflation is in progress. There are a number of checks
1777 // as part of the protocol to make sure that the calling thread has
1778 // not lost the race to a contending thread or to a thread that just
1779 // wants to use the ObjectMonitor*.
1780 //
1781 // The ObjectMonitor has been successfully async deflated when:
1782 // (owner == DEFLATER_MARKER && ref_count < 0)
1783 // Contending threads or ObjectMonitor* using threads that see those
1784 // values know to retry their operation.
1785 //
1786 bool ObjectSynchronizer::deflate_monitor_using_JT(ObjectMonitor* mid,
1787                                                   ObjectMonitor** freeHeadp,
1788                                                   ObjectMonitor** freeTailp) {
1789   assert(AsyncDeflateIdleMonitors, "sanity check");
1790   assert(Thread::current()->is_Java_thread(), "precondition");
1791   // A newly allocated ObjectMonitor should not be seen here so we
1792   // avoid an endless inflate/deflate cycle.
1793   assert(mid->is_old(), "must be old: allocation_state=%d",
1794          (int) mid->allocation_state());
1795 
1796   if (mid->is_busy() || mid->ref_count() != 0) {
1797     // Easy checks are first - the ObjectMonitor is busy or ObjectMonitor*
1798     // is in use so no deflation.
1799     return false;
1800   }
1801 
1802   if (Atomic::replace_if_null(DEFLATER_MARKER, &(mid->_owner))) {
1803     // ObjectMonitor is not owned by another thread. Our setting
1804     // owner to DEFLATER_MARKER forces any contending thread through
1805     // the slow path. This is just the first part of the async
1806     // deflation dance.
1807 
1808     if (mid->_contentions != 0 || mid->_waiters != 0) {
1809       // Another thread has raced to enter the ObjectMonitor after
1810       // mid->is_busy() above or has already entered and waited on
1811       // it which makes it busy so no deflation. Restore owner to
1812       // NULL if it is still DEFLATER_MARKER.
1813       Atomic::cmpxchg((void*)NULL, &mid->_owner, DEFLATER_MARKER);
1814       return false;
1815     }
1816 
1817     if (Atomic::cmpxchg(-max_jint, &mid->_ref_count, (jint)0) == 0) {
1818       // Make ref_count negative to force any contending threads or
1819       // ObjectMonitor* using threads to retry. This is the second
1820       // part of the async deflation dance.
1821 
1822       if (mid->_owner == DEFLATER_MARKER) {
1823         // If owner is still DEFLATER_MARKER, then we have successfully
1824         // signaled any contending threads to retry. If it is not, then we
1825         // have lost the race to an entering thread and the ObjectMonitor
1826         // is now busy. This is the third and final part of the async
1827         // deflation dance.
1828         // Note: This owner check solves the ABA problem with ref_count
1829         // where another thread acquired the ObjectMonitor, finished
1830         // using it and restored the ref_count to zero.
1831 
1832         // Sanity checks for the races:
1833         guarantee(mid->_contentions == 0, "must be 0: contentions=%d",
1834                   mid->_contentions);
1835         guarantee(mid->_waiters == 0, "must be 0: waiters=%d", mid->_waiters);
1836         guarantee(mid->_cxq == NULL, "must be no contending threads: cxq="
1837                   INTPTR_FORMAT, p2i(mid->_cxq));
1838         guarantee(mid->_EntryList == NULL,
1839                   "must be no entering threads: EntryList=" INTPTR_FORMAT,
1840                   p2i(mid->_EntryList));
1841 
1842         const oop obj = (oop) mid->object();
1843         if (log_is_enabled(Trace, monitorinflation)) {
1844           ResourceMark rm;
1845           log_trace(monitorinflation)("deflate_monitor_using_JT: "
1846                                       "object=" INTPTR_FORMAT ", mark="
1847                                       INTPTR_FORMAT ", type='%s'",
1848                                       p2i(obj), p2i(obj->mark()),
1849                                       obj->klass()->external_name());
1850         }
1851 
1852         // Install the old mark word if nobody else has already done it.
1853         mid->install_displaced_markword_in_object(obj);
1854         mid->clear_using_JT();
1855 
1856         assert(mid->object() == NULL, "must be NULL: object=" INTPTR_FORMAT,
1857                p2i(mid->object()));
1858         assert(mid->is_free(), "must be free: allocation_state=%d",
1859                (int) mid->allocation_state());
1860 
1861         // Move the deflated ObjectMonitor to the working free list
1862         // defined by freeHeadp and freeTailp.
1863         if (*freeHeadp == NULL) {
1864           // First one on the list.
1865           *freeHeadp = mid;
1866         }
1867         if (*freeTailp != NULL) {
1868           // We append to the list so the caller can use mid->FreeNext
1869           // to fix the linkages in its context.
1870           ObjectMonitor * prevtail = *freeTailp;
1871           // Should have been cleaned up by the caller:
1872           assert(prevtail->FreeNext == NULL, "must be NULL: FreeNext="
1873                  INTPTR_FORMAT, p2i(prevtail->FreeNext));
1874           prevtail->FreeNext = mid;
1875         }
1876         *freeTailp = mid;
1877 
1878         // At this point, mid->FreeNext still refers to its current
1879         // value and another ObjectMonitor's FreeNext field still
1880         // refers to this ObjectMonitor. Those linkages have to be
1881         // cleaned up by the caller who has the complete context.
1882 
1883         // We leave owner == DEFLATER_MARKER and ref_count < 0
1884         // to force any racing threads to retry.
1885         return true;  // Success, ObjectMonitor has been deflated.
1886       }
1887 
1888       // The owner was changed from DEFLATER_MARKER so we lost the
1889       // race since the ObjectMonitor is now busy.
1890 
1891       // Add back max_jint to restore the ref_count field to its
1892       // proper value (which may not be what we saw above):
1893       Atomic::add(max_jint, &mid->_ref_count);
1894 
1895       assert(mid->ref_count() >= 0, "must not be negative: ref_count=%d",
1896              mid->ref_count());
1897       return false;
1898     }
1899 
1900     // The ref_count was no longer 0 so we lost the race since the
1901     // ObjectMonitor is now busy or the ObjectMonitor* is now is use.
1902     // Restore owner to NULL if it is still DEFLATER_MARKER:
1903     Atomic::cmpxchg((void*)NULL, &mid->_owner, DEFLATER_MARKER);
1904   }
1905 
1906   // The owner field is no longer NULL so we lost the race since the
1907   // ObjectMonitor is now busy.
1908   return false;
1909 }
1910 
1911 // Walk a given monitor list, and deflate idle monitors
1912 // The given list could be a per-thread list or a global list
1913 // Caller acquires gListLock as needed.
1914 //
1915 // In the case of parallel processing of thread local monitor lists,
1916 // work is done by Threads::parallel_threads_do() which ensures that
1917 // each Java thread is processed by exactly one worker thread, and
1918 // thus avoid conflicts that would arise when worker threads would
1919 // process the same monitor lists concurrently.
1920 //
1921 // See also ParallelSPCleanupTask and
1922 // SafepointSynchronize::do_cleanup_tasks() in safepoint.cpp and
1923 // Threads::parallel_java_threads_do() in thread.cpp.
1924 int ObjectSynchronizer::deflate_monitor_list(ObjectMonitor** listHeadp,
1925                                              ObjectMonitor** freeHeadp,
1926                                              ObjectMonitor** freeTailp) {
1927   ObjectMonitor* mid;
1928   ObjectMonitor* next;
1929   ObjectMonitor* cur_mid_in_use = NULL;
1930   int deflated_count = 0;


1934     if (obj != NULL && deflate_monitor(mid, obj, freeHeadp, freeTailp)) {
1935       // if deflate_monitor succeeded,
1936       // extract from per-thread in-use list
1937       if (mid == *listHeadp) {
1938         *listHeadp = mid->FreeNext;
1939       } else if (cur_mid_in_use != NULL) {
1940         cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1941       }
1942       next = mid->FreeNext;
1943       mid->FreeNext = NULL;  // This mid is current tail in the freeHeadp list
1944       mid = next;
1945       deflated_count++;
1946     } else {
1947       cur_mid_in_use = mid;
1948       mid = mid->FreeNext;
1949     }
1950   }
1951   return deflated_count;
1952 }
1953 
1954 // Walk a given ObjectMonitor list and deflate idle ObjectMonitors using
1955 // a JavaThread. Returns the number of deflated ObjectMonitors. The given
1956 // list could be a per-thread in-use list or the global in-use list.
1957 // Caller acquires gListLock as appropriate. If a safepoint has started,
1958 // then we save state via savedMidInUsep and return to the caller to
1959 // honor the safepoint.
1960 //
1961 int ObjectSynchronizer::deflate_monitor_list_using_JT(ObjectMonitor** listHeadp,
1962                                                       ObjectMonitor** freeHeadp,
1963                                                       ObjectMonitor** freeTailp,
1964                                                       ObjectMonitor** savedMidInUsep) {
1965   assert(AsyncDeflateIdleMonitors, "sanity check");
1966   assert(Thread::current()->is_Java_thread(), "precondition");
1967 
1968   ObjectMonitor* mid;
1969   ObjectMonitor* next;
1970   ObjectMonitor* cur_mid_in_use = NULL;
1971   int deflated_count = 0;
1972 
1973   if (*savedMidInUsep == NULL) {
1974     // No saved state so start at the beginning.
1975     mid = *listHeadp;
1976   } else {
1977     // We're restarting after a safepoint so restore the necessary state
1978     // before we resume.
1979     cur_mid_in_use = *savedMidInUsep;
1980     mid = cur_mid_in_use->FreeNext;
1981   }
1982   while (mid != NULL) {
1983     // Only try to deflate if there is an associated Java object and if
1984     // mid is old (is not newly allocated and is not newly freed).
1985     if (mid->object() != NULL && mid->is_old() &&
1986         deflate_monitor_using_JT(mid, freeHeadp, freeTailp)) {
1987       // Deflation succeeded so update the in-use list.
1988       if (mid == *listHeadp) {
1989         *listHeadp = mid->FreeNext;
1990       } else if (cur_mid_in_use != NULL) {
1991         // Maintain the current in-use list.
1992         cur_mid_in_use->FreeNext = mid->FreeNext;
1993       }
1994       next = mid->FreeNext;
1995       mid->FreeNext = NULL;
1996       // At this point mid is disconnected from the in-use list
1997       // and is the current tail in the freeHeadp list.
1998       mid = next;
1999       deflated_count++;
2000     } else {
2001       // mid is considered in-use if it does not have an associated
2002       // Java object or mid is not old or deflation did not succeed.
2003       // A mid->is_new() node can be seen here when it is freshly
2004       // returned by omAlloc() (and skips the deflation code path).
2005       // A mid->is_old() node can be seen here when deflation failed.
2006       // A mid->is_free() node can be seen here when a fresh node from
2007       // omAlloc() is released by omRelease() due to losing the race
2008       // in inflate().
2009 
2010       cur_mid_in_use = mid;
2011       mid = mid->FreeNext;
2012 
2013       if (SafepointSynchronize::is_synchronizing() &&
2014           cur_mid_in_use != *listHeadp && cur_mid_in_use->is_old()) {
2015         // If a safepoint has started and cur_mid_in_use is not the list
2016         // head and is old, then it is safe to use as saved state. Return
2017         // to the caller so gListLock can be dropped as appropriate
2018         // before blocking.
2019         *savedMidInUsep = cur_mid_in_use;
2020         return deflated_count;
2021       }
2022     }
2023   }
2024   // We finished the list without a safepoint starting so there's
2025   // no need to save state.
2026   *savedMidInUsep = NULL;
2027   return deflated_count;
2028 }
2029 
2030 void ObjectSynchronizer::prepare_deflate_idle_monitors(DeflateMonitorCounters* counters) {
2031   counters->nInuse = 0;              // currently associated with objects
2032   counters->nInCirculation = 0;      // extant
2033   counters->nScavenged = 0;          // reclaimed (global and per-thread)
2034   counters->perThreadScavenged = 0;  // per-thread scavenge total
2035   counters->perThreadTimes = 0.0;    // per-thread scavenge times
2036 }
2037 
2038 void ObjectSynchronizer::deflate_idle_monitors(DeflateMonitorCounters* counters) {
2039   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2040 
2041   if (AsyncDeflateIdleMonitors) {
2042     // Nothing to do when global idle ObjectMonitors are deflated using
2043     // a JavaThread unless a special cleanup has been requested.
2044     if (!is_cleanup_requested()) {
2045       return;
2046     }
2047   }
2048 
2049   bool deflated = false;
2050 
2051   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged monitors
2052   ObjectMonitor * freeTailp = NULL;
2053   elapsedTimer timer;
2054 
2055   if (log_is_enabled(Info, monitorinflation)) {
2056     timer.start();
2057   }
2058 
2059   // Prevent omFlush from changing mids in Thread dtor's during deflation
2060   // And in case the vm thread is acquiring a lock during a safepoint
2061   // See e.g. 6320749
2062   Thread::muxAcquire(&gListLock, "deflate_idle_monitors");
2063 
2064   // Note: the thread-local monitors lists get deflated in
2065   // a separate pass. See deflate_thread_local_monitors().
2066 
2067   // For moribund threads, scan gOmInUseList
2068   int deflated_count = 0;


2081     // constant-time list splice - prepend scavenged segment to gFreeList
2082     freeTailp->FreeNext = gFreeList;
2083     gFreeList = freeHeadp;
2084   }
2085   Thread::muxRelease(&gListLock);
2086   timer.stop();
2087 
2088   LogStreamHandle(Debug, monitorinflation) lsh_debug;
2089   LogStreamHandle(Info, monitorinflation) lsh_info;
2090   LogStream * ls = NULL;
2091   if (log_is_enabled(Debug, monitorinflation)) {
2092     ls = &lsh_debug;
2093   } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
2094     ls = &lsh_info;
2095   }
2096   if (ls != NULL) {
2097     ls->print_cr("deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count);
2098   }
2099 }
2100 
2101 // Deflate global idle ObjectMonitors using a JavaThread.
2102 //
2103 void ObjectSynchronizer::deflate_global_idle_monitors_using_JT() {
2104   assert(AsyncDeflateIdleMonitors, "sanity check");
2105   assert(Thread::current()->is_Java_thread(), "precondition");
2106   JavaThread * self = JavaThread::current();
2107 
2108   _gOmShouldDeflateIdleMonitors = false;
2109 
2110   deflate_common_idle_monitors_using_JT(true /* is_global */, self);
2111 }
2112 
2113 // Deflate per-thread idle ObjectMonitors using a JavaThread.
2114 //
2115 void ObjectSynchronizer::deflate_per_thread_idle_monitors_using_JT() {
2116   assert(AsyncDeflateIdleMonitors, "sanity check");
2117   assert(Thread::current()->is_Java_thread(), "precondition");
2118   JavaThread * self = JavaThread::current();
2119 
2120   self->omShouldDeflateIdleMonitors = false;
2121 
2122   deflate_common_idle_monitors_using_JT(false /* !is_global */, self);
2123 }
2124 
2125 // Deflate global or per-thread idle ObjectMonitors using a JavaThread.
2126 //
2127 void ObjectSynchronizer::deflate_common_idle_monitors_using_JT(bool is_global, JavaThread * self) {
2128   int deflated_count = 0;
2129   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged ObjectMonitors
2130   ObjectMonitor * freeTailp = NULL;
2131   ObjectMonitor * savedMidInUsep = NULL;
2132   elapsedTimer timer;
2133 
2134   if (log_is_enabled(Info, monitorinflation)) {
2135     timer.start();
2136   }
2137 
2138   if (is_global) {
2139     Thread::muxAcquire(&gListLock, "deflate_global_idle_monitors_using_JT(1)");
2140     OM_PERFDATA_OP(MonExtant, set_value(gOmInUseCount));
2141   } else {
2142     OM_PERFDATA_OP(MonExtant, inc(self->omInUseCount));
2143   }
2144 
2145   do {
2146     int local_deflated_count;
2147     if (is_global) {
2148       local_deflated_count = deflate_monitor_list_using_JT((ObjectMonitor **)&gOmInUseList, &freeHeadp, &freeTailp, &savedMidInUsep);
2149       gOmInUseCount -= local_deflated_count;
2150     } else {
2151       local_deflated_count = deflate_monitor_list_using_JT(self->omInUseList_addr(), &freeHeadp, &freeTailp, &savedMidInUsep);
2152       self->omInUseCount -= local_deflated_count;
2153     }
2154     deflated_count += local_deflated_count;
2155 
2156     if (freeHeadp != NULL) {
2157       // Move the scavenged ObjectMonitors to the global free list.
2158       guarantee(freeTailp != NULL && local_deflated_count > 0, "freeTailp=" INTPTR_FORMAT ", local_deflated_count=%d", p2i(freeTailp), local_deflated_count);
2159       assert(freeTailp->FreeNext == NULL, "invariant");
2160 
2161       if (!is_global) {
2162         Thread::muxAcquire(&gListLock, "deflate_per_thread_idle_monitors_using_JT(2)");
2163       }
2164       // Constant-time list splice - prepend scavenged segment to gFreeList.
2165       freeTailp->FreeNext = gFreeList;
2166       gFreeList = freeHeadp;
2167 
2168       gMonitorFreeCount += local_deflated_count;
2169       OM_PERFDATA_OP(Deflations, inc(local_deflated_count));
2170       if (!is_global) {
2171         Thread::muxRelease(&gListLock);
2172       }
2173     }
2174 
2175     if (savedMidInUsep != NULL) {
2176       // deflate_monitor_list_using_JT() detected a safepoint starting.
2177       if (is_global) {
2178         Thread::muxRelease(&gListLock);
2179       }
2180       timer.stop();
2181       {
2182         if (is_global) {
2183           log_debug(monitorinflation)("pausing deflation of global idle monitors for a safepoint.");
2184         } else {
2185           log_debug(monitorinflation)("jt=" INTPTR_FORMAT ": pausing deflation of per-thread idle monitors for a safepoint.", p2i(self));
2186         }
2187         assert(SafepointSynchronize::is_synchronizing(), "sanity check");
2188         ThreadBlockInVM blocker(self);
2189       }
2190       // Prepare for another loop after the safepoint.
2191       freeHeadp = NULL;
2192       freeTailp = NULL;
2193       if (log_is_enabled(Info, monitorinflation)) {
2194         timer.start();
2195       }
2196       if (is_global) {
2197         Thread::muxAcquire(&gListLock, "deflate_global_idle_monitors_using_JT(3)");
2198       }
2199     }
2200   } while (savedMidInUsep != NULL);
2201   if (is_global) {
2202     Thread::muxRelease(&gListLock);
2203   }
2204   timer.stop();
2205 
2206   LogStreamHandle(Debug, monitorinflation) lsh_debug;
2207   LogStreamHandle(Info, monitorinflation) lsh_info;
2208   LogStream * ls = NULL;
2209   if (log_is_enabled(Debug, monitorinflation)) {
2210     ls = &lsh_debug;
2211   } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
2212     ls = &lsh_info;
2213   }
2214   if (ls != NULL) {
2215     if (is_global) {
2216       ls->print_cr("async-deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count);
2217     } else {
2218       ls->print_cr("jt=" INTPTR_FORMAT ": async-deflating per-thread idle monitors, %3.7f secs, %d monitors", p2i(self), timer.seconds(), deflated_count);
2219     }
2220   }
2221 }
2222 
2223 void ObjectSynchronizer::finish_deflate_idle_monitors(DeflateMonitorCounters* counters) {
2224   // Report the cumulative time for deflating each thread's idle
2225   // monitors. Note: if the work is split among more than one
2226   // worker thread, then the reported time will likely be more
2227   // than a beginning to end measurement of the phase.
2228   // Note: AsyncDeflateIdleMonitors only deflates per-thread idle
2229   // monitors at a safepoint when a special cleanup has been requested.
2230   log_info(safepoint, cleanup)("deflating per-thread idle monitors, %3.7f secs, monitors=%d", counters->perThreadTimes, counters->perThreadScavenged);
2231 
2232   bool needs_special_cleanup = is_cleanup_requested();
2233   if (!AsyncDeflateIdleMonitors || needs_special_cleanup) {
2234     // AsyncDeflateIdleMonitors does not use these counters unless
2235     // there is a special cleanup request.
2236 
2237     gMonitorFreeCount += counters->nScavenged;
2238 
2239     OM_PERFDATA_OP(Deflations, inc(counters->nScavenged));
2240     OM_PERFDATA_OP(MonExtant, set_value(counters->nInCirculation));
2241   }
2242 
2243   if (log_is_enabled(Debug, monitorinflation)) {
2244     // exit_globals()'s call to audit_and_print_stats() is done
2245     // at the Info level.
2246     ObjectSynchronizer::audit_and_print_stats(false /* on_exit */);
2247   } else if (log_is_enabled(Info, monitorinflation)) {
2248     Thread::muxAcquire(&gListLock, "finish_deflate_idle_monitors");
2249     log_info(monitorinflation)("gMonitorPopulation=%d, gOmInUseCount=%d, "
2250                                "gMonitorFreeCount=%d", gMonitorPopulation,
2251                                gOmInUseCount, gMonitorFreeCount);
2252     Thread::muxRelease(&gListLock);
2253   }
2254 
2255   ForceMonitorScavenge = 0;    // Reset




2256   GVars.stwRandom = os::random();
2257   GVars.stwCycle++;
2258   if (needs_special_cleanup) {
2259     set_is_cleanup_requested(false);  // special clean up is done
2260   }
2261 }
2262 
2263 void ObjectSynchronizer::deflate_thread_local_monitors(Thread* thread, DeflateMonitorCounters* counters) {
2264   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2265 
2266   if (AsyncDeflateIdleMonitors) {
2267     if (!is_cleanup_requested()) {
2268       // Mark the JavaThread for idle monitor cleanup if a special
2269       // cleanup has NOT been requested.
2270       if (thread->omInUseCount > 0) {
2271         // This JavaThread is using monitors so mark it.
2272         thread->omShouldDeflateIdleMonitors = true;
2273       }
2274       return;
2275     }
2276   }
2277 
2278   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged monitors
2279   ObjectMonitor * freeTailp = NULL;
2280   elapsedTimer timer;
2281 
2282   if (log_is_enabled(Info, safepoint, cleanup) ||
2283       log_is_enabled(Info, monitorinflation)) {
2284     timer.start();
2285   }
2286 
2287   int deflated_count = deflate_monitor_list(thread->omInUseList_addr(), &freeHeadp, &freeTailp);
2288 
2289   Thread::muxAcquire(&gListLock, "deflate_thread_local_monitors");
2290 
2291   // Adjust counters
2292   counters->nInCirculation += thread->omInUseCount;
2293   thread->omInUseCount -= deflated_count;
2294   counters->nScavenged += deflated_count;
2295   counters->nInuse += thread->omInUseCount;
2296   counters->perThreadScavenged += deflated_count;
2297 


2466   } else {
2467     log_error(monitorinflation)("found monitor list errors: error_cnt=%d", error_cnt);
2468   }
2469 
2470   if ((on_exit && log_is_enabled(Info, monitorinflation)) ||
2471       (!on_exit && log_is_enabled(Trace, monitorinflation))) {
2472     // When exiting this log output is at the Info level. When called
2473     // at a safepoint, this log output is at the Trace level since
2474     // there can be a lot of it.
2475     log_in_use_monitor_details(ls, on_exit);
2476   }
2477 
2478   ls->flush();
2479 
2480   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
2481 }
2482 
2483 // Check a free monitor entry; log any errors.
2484 void ObjectSynchronizer::chk_free_entry(JavaThread * jt, ObjectMonitor * n,
2485                                         outputStream * out, int *error_cnt_p) {
2486   if ((!AsyncDeflateIdleMonitors && n->is_busy()) ||
2487       (AsyncDeflateIdleMonitors && n->is_busy_async())) {
2488     if (jt != NULL) {
2489       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2490                     ": free per-thread monitor must not be busy.", p2i(jt),
2491                     p2i(n));
2492     } else {
2493       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2494                     "must not be busy.", p2i(n));
2495     }
2496     *error_cnt_p = *error_cnt_p + 1;
2497   }
2498   if (n->header() != NULL) {
2499     if (jt != NULL) {
2500       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2501                     ": free per-thread monitor must have NULL _header "
2502                     "field: _header=" INTPTR_FORMAT, p2i(jt), p2i(n),
2503                     p2i(n->header()));
2504       *error_cnt_p = *error_cnt_p + 1;
2505     } else if (!AsyncDeflateIdleMonitors) {
2506       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2507                     "must have NULL _header field: _header=" INTPTR_FORMAT,
2508                     p2i(n), p2i(n->header()));

2509       *error_cnt_p = *error_cnt_p + 1;
2510     }
2511   }
2512   if (n->object() != NULL) {
2513     if (jt != NULL) {
2514       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2515                     ": free per-thread monitor must have NULL _object "
2516                     "field: _object=" INTPTR_FORMAT, p2i(jt), p2i(n),
2517                     p2i(n->object()));
2518     } else {
2519       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2520                     "must have NULL _object field: _object=" INTPTR_FORMAT,
2521                     p2i(n), p2i(n->object()));
2522     }
2523     *error_cnt_p = *error_cnt_p + 1;
2524   }
2525 }
2526 
2527 // Check the global free list and count; log the results of the checks.
2528 void ObjectSynchronizer::chk_global_free_list_and_count(outputStream * out,
2529                                                         int *error_cnt_p) {
2530   int chkMonitorFreeCount = 0;
2531   for (ObjectMonitor * n = gFreeList; n != NULL; n = n->FreeNext) {


2657     out->print_cr("ERROR: jt=" INTPTR_FORMAT ": omInUseCount=%d is not "
2658                   "equal to chkOmInUseCount=%d", p2i(jt), jt->omInUseCount,
2659                   chkOmInUseCount);
2660     *error_cnt_p = *error_cnt_p + 1;
2661   }
2662 }
2663 
2664 // Log details about ObjectMonitors on the in-use lists. The 'BHL'
2665 // flags indicate why the entry is in-use, 'object' and 'object type'
2666 // indicate the associated object and its type.
2667 void ObjectSynchronizer::log_in_use_monitor_details(outputStream * out,
2668                                                     bool on_exit) {
2669   if (!on_exit) {
2670     // Not at VM exit so grab the global list lock.
2671     Thread::muxAcquire(&gListLock, "log_in_use_monitor_details");
2672   }
2673 
2674   if (gOmInUseCount > 0) {
2675     out->print_cr("In-use global monitor info:");
2676     out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2677     out->print_cr("%18s  %s  %7s  %18s  %18s",
2678                   "monitor", "BHL", "ref_cnt", "object", "object type");
2679     out->print_cr("==================  ===  =======  ==================  ==================");
2680     for (ObjectMonitor * n = gOmInUseList; n != NULL; n = n->FreeNext) {
2681       const oop obj = (oop) n->object();
2682       const markOop mark = n->header();
2683       ResourceMark rm;
2684       out->print_cr(INTPTR_FORMAT "  %d%d%d  %7d  " INTPTR_FORMAT "  %s",
2685                     p2i(n), n->is_busy() != 0, mark->hash() != 0,
2686                     n->owner() != NULL, (int)n->ref_count(), p2i(obj),
2687                     obj->klass()->external_name());
2688     }
2689   }
2690 
2691   if (!on_exit) {
2692     Thread::muxRelease(&gListLock);
2693   }
2694 
2695   out->print_cr("In-use per-thread monitor info:");
2696   out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2697   out->print_cr("%18s  %18s  %s  %7s  %18s  %18s",
2698                 "jt", "monitor", "BHL", "ref_cnt", "object", "object type");
2699   out->print_cr("==================  ==================  ===  =======  ==================  ==================");
2700   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2701     for (ObjectMonitor * n = jt->omInUseList; n != NULL; n = n->FreeNext) {
2702       const oop obj = (oop) n->object();
2703       const markOop mark = n->header();
2704       ResourceMark rm;
2705       out->print_cr(INTPTR_FORMAT "  " INTPTR_FORMAT "  %d%d%d  %7d  "
2706                     INTPTR_FORMAT "  %s", p2i(jt), p2i(n), n->is_busy() != 0,
2707                     mark->hash() != 0, n->owner() != NULL, (int)n->ref_count(),
2708                     p2i(obj), obj->klass()->external_name());
2709     }
2710   }
2711 
2712   out->flush();
2713 }
2714 
2715 // Log counts for the global and per-thread monitor lists and return
2716 // the population count.
2717 int ObjectSynchronizer::log_monitor_list_counts(outputStream * out) {
2718   int popCount = 0;
2719   out->print_cr("%18s  %10s  %10s  %10s",
2720                 "Global Lists:", "InUse", "Free", "Total");
2721   out->print_cr("==================  ==========  ==========  ==========");
2722   out->print_cr("%18s  %10d  %10d  %10d", "",
2723                 gOmInUseCount, gMonitorFreeCount, gMonitorPopulation);
2724   popCount += gOmInUseCount + gMonitorFreeCount;
2725 
2726   out->print_cr("%18s  %10s  %10s  %10s",
2727                 "Per-Thread Lists:", "InUse", "Free", "Provision");
2728   out->print_cr("==================  ==========  ==========  ==========");


< prev index next >