< prev index next >

src/hotspot/share/runtime/synchronizer.cpp

Print this page
rev 54109 : Add logging to ObjectSynchronizer::omFlush(), add global count logging at Info level to ObjectSynchronizer::finish_deflate_idle_monitors(); for monitorinflation logging, switch from cumulative "deflating per-thread idle monitors" mesgs to per-thread "deflating per-thread idle monitors" mesgs; fix timer bug in deflate_thread_local_monitors() where time to acquire gListLock wasn't counted; fix misc typos.
rev 54110 : Checkpoint latest preliminary review patches for full OpenJDK review.


 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((address)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((address)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 is strictly immutable.
 753     // It can NOT be changed in ANY cases. So we have
 754     // to inflate the header into heavyweight monitor
 755     // even the current thread owns the lock. The reason
 756     // is the BasicLock (stack slot) will be asynchronously
 757     // read by other threads during the inflate() function.
 758     // Any change to stack may not propagate to other threads
 759     // correctly.
 760   }
 761 
 762   // Inflate the monitor to set hash code
 763   monitor = inflate(Self, obj, inflate_cause_hash_code);


 764   // Load displaced header and check it has hash code
 765   mark = monitor->header();
 766   assert(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i((address)mark));
 767   hash = mark->hash();
 768   if (hash == 0) {
 769     hash = get_next_hash(Self, obj);
 770     temp = mark->copy_set_hash(hash); // merge hash code into header
 771     assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i((address)temp));
 772     test = Atomic::cmpxchg(temp, monitor->header_addr(), mark);
 773     if (test != mark) {
 774       // The only update to the header in the monitor (outside GC)
 775       // is install the hash code. If someone add new usage of
 776       // displaced header, please update this code
 777       hash = test->hash();
 778       assert(test->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i((address)test));
 779       assert(hash != 0, "Trivial unexpected object/monitor header usage.");
 780     }
 781   }
 782   // We finally get the hash
 783   return hash;
 784 }
 785 
 786 // Deprecated -- use FastHashCode() instead.
 787 
 788 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
 789   return FastHashCode(Thread::current(), obj());
 790 }
 791 
 792 
 793 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread,
 794                                                    Handle h_obj) {
 795   if (UseBiasedLocking) {
 796     BiasedLocking::revoke_and_rebias(h_obj, false, thread);
 797     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 798   }
 799 
 800   assert(thread == JavaThread::current(), "Can only be called on current thread");
 801   oop obj = h_obj();
 802 

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






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

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


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







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

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


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






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

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










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


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

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














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

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




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

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


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

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


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

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

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

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




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

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


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

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










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





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











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


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


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











1468     // prepare m for installation - set monitor to initial state
1469     m->Recycle();
1470     m->set_header(mark);
1471     m->set_owner(NULL);
1472     m->set_object(object);
1473     m->_recursions   = 0;
1474     m->_Responsible  = NULL;
1475     m->_SpinDuration = ObjectMonitor::Knob_SpinLimit;       // consider: keep metastats by type/class
1476 
1477     if (object->cas_set_mark(markOopDesc::encode(m), mark) != mark) {
1478       m->set_header(NULL);
1479       m->set_object(NULL);
1480       m->Recycle();
1481       omRelease(Self, m, true);
1482       m = NULL;
1483       continue;
1484       // interference - the markword changed - just retry.
1485       // The state-transitions are one-way, so there's no chance of
1486       // live-lock -- "Inflated" is an absorbing state.
1487     }
1488 
1489     // Hopefully the performance counters are allocated on distinct
1490     // cache lines to avoid false sharing on MP systems ...
1491     OM_PERFDATA_OP(Inflations, inc());
1492     if (log_is_enabled(Trace, monitorinflation)) {
1493       ResourceMark rm(Self);
1494       lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark="
1495                    INTPTR_FORMAT ", type='%s'", p2i(object),
1496                    p2i(object->mark()), object->klass()->external_name());
1497     }
1498     if (event.should_commit()) {
1499       post_monitor_inflate_event(&event, object, cause);
1500     }
1501     return m;

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
























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

1557 
1558     // Move the object to the working free list defined by freeHeadp, freeTailp
1559     if (*freeHeadp == NULL) *freeHeadp = mid;
1560     if (*freeTailp != NULL) {
1561       ObjectMonitor * prevtail = *freeTailp;
1562       assert(prevtail->FreeNext == NULL, "cleaned up deflated?");
1563       prevtail->FreeNext = mid;
1564     }
1565     *freeTailp = mid;
1566     deflated = true;
1567   }
1568   return deflated;
1569 }
1570 






























































































































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


1594     if (obj != NULL && deflate_monitor(mid, obj, freeHeadp, freeTailp)) {
1595       // if deflate_monitor succeeded,
1596       // extract from per-thread in-use list
1597       if (mid == *listHeadp) {
1598         *listHeadp = mid->FreeNext;
1599       } else if (cur_mid_in_use != NULL) {
1600         cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1601       }
1602       next = mid->FreeNext;
1603       mid->FreeNext = NULL;  // This mid is current tail in the freeHeadp list
1604       mid = next;
1605       deflated_count++;
1606     } else {
1607       cur_mid_in_use = mid;
1608       mid = mid->FreeNext;
1609     }
1610   }
1611   return deflated_count;
1612 }
1613 

















































































1614 void ObjectSynchronizer::prepare_deflate_idle_monitors(DeflateMonitorCounters* counters) {
1615   counters->nInuse = 0;              // currently associated with objects
1616   counters->nInCirculation = 0;      // extant
1617   counters->nScavenged = 0;          // reclaimed (global and per-thread)
1618   counters->perThreadScavenged = 0;  // per-thread scavenge total
1619   counters->perThreadTimes = 0.0;    // per-thread scavenge times
1620 }
1621 
1622 void ObjectSynchronizer::deflate_idle_monitors(DeflateMonitorCounters* counters) {

1623   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1624   bool deflated = false;
1625 
1626   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged monitors
1627   ObjectMonitor * freeTailp = NULL;
1628   elapsedTimer timer;
1629 
1630   if (log_is_enabled(Info, monitorinflation)) {
1631     timer.start();
1632   }
1633 
1634   // Prevent omFlush from changing mids in Thread dtor's during deflation
1635   // And in case the vm thread is acquiring a lock during a safepoint
1636   // See e.g. 6320749
1637   Thread::muxAcquire(&gListLock, "deflate_idle_monitors");
1638 
1639   // Note: the thread-local monitors lists get deflated in
1640   // a separate pass. See deflate_thread_local_monitors().
1641 
1642   // For moribund threads, scan gOmInUseList


1656     // constant-time list splice - prepend scavenged segment to gFreeList
1657     freeTailp->FreeNext = gFreeList;
1658     gFreeList = freeHeadp;
1659   }
1660   Thread::muxRelease(&gListLock);
1661   timer.stop();
1662 
1663   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1664   LogStreamHandle(Info, monitorinflation) lsh_info;
1665   LogStream * ls = NULL;
1666   if (log_is_enabled(Debug, monitorinflation)) {
1667     ls = &lsh_debug;
1668   } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
1669     ls = &lsh_info;
1670   }
1671   if (ls != NULL) {
1672     ls->print_cr("deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count);
1673   }
1674 }
1675 

















































































































































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


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





1683   gMonitorFreeCount += counters->nScavenged;
1684 




1685   if (log_is_enabled(Debug, monitorinflation)) {
1686     // exit_globals()'s call to audit_and_print_stats() is done
1687     // at the Info level.
1688     ObjectSynchronizer::audit_and_print_stats(false /* on_exit */);
1689   } else if (log_is_enabled(Info, monitorinflation)) {
1690     Thread::muxAcquire(&gListLock, "finish_deflate_idle_monitors");
1691     log_info(monitorinflation)("gMonitorPopulation=%d, gOmInUseCount=%d, "
1692                                "gMonitorFreeCount=%d", gMonitorPopulation,
1693                                gOmInUseCount, gMonitorFreeCount);
1694     Thread::muxRelease(&gListLock);
1695   }
1696 
1697   ForceMonitorScavenge = 0;    // Reset
1698 
1699   OM_PERFDATA_OP(Deflations, inc(counters->nScavenged));
1700   OM_PERFDATA_OP(MonExtant, set_value(counters->nInCirculation));
1701 
1702   GVars.stwRandom = os::random();
1703   GVars.stwCycle++;



1704 }
1705 
1706 void ObjectSynchronizer::deflate_thread_local_monitors(Thread* thread, DeflateMonitorCounters* counters) {
1707   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1708 








1709   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged monitors
1710   ObjectMonitor * freeTailp = NULL;
1711   elapsedTimer timer;
1712 
1713   if (log_is_enabled(Info, safepoint, cleanup) ||
1714       log_is_enabled(Info, monitorinflation)) {
1715     timer.start();
1716   }
1717 
1718   int deflated_count = deflate_monitor_list(thread->omInUseList_addr(), &freeHeadp, &freeTailp);
1719 
1720   Thread::muxAcquire(&gListLock, "deflate_thread_local_monitors(1)");
1721 
1722   // Adjust counters
1723   counters->nInCirculation += thread->omInUseCount;
1724   thread->omInUseCount -= deflated_count;
1725   counters->nScavenged += deflated_count;
1726   counters->nInuse += thread->omInUseCount;
1727   counters->perThreadScavenged += deflated_count;
1728 


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

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


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

2122     }
2123   }
2124 
2125   if (!on_exit) {
2126     Thread::muxRelease(&gListLock);
2127   }
2128 
2129   out->print_cr("In-use per-thread monitor info:");
2130   out->print_cr("(B -> is_busy, H -> has hashcode, L -> lock status)");
2131   out->print_cr("%18s  %18s  %s  %18s  %18s",
2132                 "jt", "monitor", "BHL", "object", "object type");
2133   out->print_cr("==================  ==================  ===  ==================  ==================");
2134   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2135     for (ObjectMonitor * n = jt->omInUseList; n != NULL; n = n->FreeNext) {
2136       const oop obj = (oop) n->object();
2137       const markOop mark = n->header();
2138       ResourceMark rm;
2139       out->print_cr(INTPTR_FORMAT "  " INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT
2140                     "  %s", p2i(jt), p2i(n), n->is_busy() != 0,
2141                     mark->hash() != 0, n->owner() != NULL, p2i(obj),
2142                     obj->klass()->external_name());
2143     }
2144   }
2145 
2146   out->flush();
2147 }
2148 
2149 // Log counts for the global and per-thread monitor lists and return
2150 // the population count.
2151 int ObjectSynchronizer::log_monitor_list_counts(outputStream * out) {
2152   int popCount = 0;
2153   out->print_cr("%18s  %10s  %10s  %10s",
2154                 "Global Lists:", "InUse", "Free", "Total");
2155   out->print_cr("==================  ==========  ==========  ==========");
2156   out->print_cr("%18s  %10d  %10d  %10d", "",
2157                 gOmInUseCount, gMonitorFreeCount, gMonitorPopulation);
2158   popCount += gOmInUseCount + gMonitorFreeCount;
2159 
2160   out->print_cr("%18s  %10s  %10s  %10s",
2161                 "Per-Thread Lists:", "InUse", "Free", "Provision");
2162   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   bool do_loop = true;
 354   while (do_loop) {
 355     markOop mark = obj->mark();
 356     assert(!mark->has_bias_pattern(), "should not see bias pattern here");
 357 
 358     if (mark->is_neutral()) {
 359       // Anticipate successful CAS -- the ST of the displaced mark must
 360       // be visible <= the ST performed by the CAS.
 361       lock->set_displaced_header(mark);
 362       if (mark == obj()->cas_set_mark((markOop) lock, mark)) {
 363         return;
 364       }
 365       // Fall through to inflate() ...
 366     } else if (mark->has_locker() &&
 367                THREAD->is_lock_owned((address)mark->locker())) {
 368       assert(lock != mark->locker(), "must not re-lock the same lock");
 369       assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock");
 370       lock->set_displaced_header(NULL);
 371       return;
 372     }
 373 
 374     // The object header will never be displaced to this lock,
 375     // so it does not matter what the value is, except that it
 376     // must be non-zero to avoid looking like a re-entrant lock,
 377     // and must not look locked either.
 378     lock->set_displaced_header(markOopDesc::unused_mark());
 379     ObjectMonitorHandle omh;
 380     inflate(&omh, THREAD, obj(), inflate_cause_monitor_enter);
 381     do_loop = !omh.om_ptr()->enter(THREAD);
 382   }
 383 }
 384 
 385 // This routine is used to handle interpreter/compiler slow case
 386 // We don't need to use fast path here, because it must have
 387 // failed in the interpreter/compiler code. Simply use the heavy
 388 // weight monitor should be ok, unless someone find otherwise.
 389 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
 390   fast_exit(object, lock, THREAD);
 391 }
 392 
 393 // -----------------------------------------------------------------------------
 394 // Class Loader  support to workaround deadlocks on the class loader lock objects
 395 // Also used by GC
 396 // complete_exit()/reenter() are used to wait on a nested lock
 397 // i.e. to give up an outer lock completely and then re-enter
 398 // Used when holding nested locks - lock acquisition order: lock1 then lock2
 399 //  1) complete_exit lock1 - saving recursion count
 400 //  2) wait on lock2
 401 //  3) when notified on lock2, unlock lock2
 402 //  4) reenter lock1 with original recursion count
 403 //  5) lock lock2
 404 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 405 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) {
 406   if (UseBiasedLocking) {
 407     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 408     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 409   }
 410 
 411   ObjectMonitorHandle omh;
 412   inflate(&omh, THREAD, obj(), inflate_cause_vm_internal);
 413   intptr_t ret_code = omh.om_ptr()->complete_exit(THREAD);
 414   return ret_code;
 415 }
 416 
 417 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 418 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) {
 419   if (UseBiasedLocking) {
 420     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 421     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 422   }
 423 
 424   bool do_loop = true;
 425   while (do_loop) {
 426     ObjectMonitorHandle omh;
 427     inflate(&omh, THREAD, obj(), inflate_cause_vm_internal);
 428     do_loop = !omh.om_ptr()->reenter(recursion, THREAD);
 429   }
 430 }
 431 // -----------------------------------------------------------------------------
 432 // JNI locks on java objects
 433 // NOTE: must use heavy weight monitor to handle jni monitor enter
 434 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) {
 435   // the current locking is from JNI instead of Java code
 436   if (UseBiasedLocking) {
 437     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 438     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 439   }
 440   THREAD->set_current_pending_monitor_is_from_java(false);
 441   bool do_loop = true;
 442   while (do_loop) {
 443     ObjectMonitorHandle omh;
 444     inflate(&omh, THREAD, obj(), inflate_cause_jni_enter);
 445     do_loop = !omh.om_ptr()->enter(THREAD);
 446   }
 447   THREAD->set_current_pending_monitor_is_from_java(true);
 448 }
 449 
 450 // NOTE: must use heavy weight monitor to handle jni monitor exit
 451 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
 452   if (UseBiasedLocking) {
 453     Handle h_obj(THREAD, obj);
 454     BiasedLocking::revoke_and_rebias(h_obj, false, THREAD);
 455     obj = h_obj();
 456   }
 457   assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 458 
 459   ObjectMonitorHandle omh;
 460   inflate(&omh, THREAD, obj, inflate_cause_jni_exit);
 461   ObjectMonitor * monitor = omh.om_ptr();
 462   // If this thread has locked the object, exit the monitor.  Note:  can't use
 463   // monitor->check(CHECK); must exit even if an exception is pending.
 464   if (monitor->check(THREAD)) {
 465     monitor->exit(true, THREAD);
 466   }
 467 }
 468 
 469 // -----------------------------------------------------------------------------
 470 // Internal VM locks on java objects
 471 // standard constructor, allows locking failures
 472 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) {
 473   _dolock = doLock;
 474   _thread = thread;
 475   debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);)
 476   _obj = obj;
 477 
 478   if (_dolock) {
 479     ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread);
 480   }
 481 }
 482 
 483 ObjectLocker::~ObjectLocker() {
 484   if (_dolock) {
 485     ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread);
 486   }
 487 }
 488 
 489 
 490 // -----------------------------------------------------------------------------
 491 //  Wait/Notify/NotifyAll
 492 // NOTE: must use heavy weight monitor to handle wait()
 493 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 494   if (UseBiasedLocking) {
 495     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 496     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 497   }
 498   if (millis < 0) {
 499     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 500   }
 501   ObjectMonitorHandle omh;
 502   inflate(&omh, THREAD, obj(), inflate_cause_wait);
 503   ObjectMonitor * monitor = omh.om_ptr();
 504 
 505   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);
 506   monitor->wait(millis, true, THREAD);
 507 
 508   // This dummy call is in place to get around dtrace bug 6254741.  Once
 509   // that's fixed we can uncomment the following line, remove the call
 510   // and change this function back into a "void" func.
 511   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 512   int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
 513   return ret_code;
 514 }
 515 
 516 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) {
 517   if (UseBiasedLocking) {
 518     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 519     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 520   }
 521   if (millis < 0) {
 522     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 523   }
 524   ObjectMonitorHandle omh;
 525   inflate(&omh, THREAD, obj(), inflate_cause_wait);
 526   omh.om_ptr()->wait(millis, false, THREAD);
 527 }
 528 
 529 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 530   if (UseBiasedLocking) {
 531     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 532     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 533   }
 534 
 535   markOop mark = obj->mark();
 536   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
 537     return;
 538   }
 539   ObjectMonitorHandle omh;
 540   inflate(&omh, THREAD, obj(), inflate_cause_notify);
 541   omh.om_ptr()->notify(THREAD);
 542 }
 543 
 544 // NOTE: see comment of notify()
 545 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 546   if (UseBiasedLocking) {
 547     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 548     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 549   }
 550 
 551   markOop mark = obj->mark();
 552   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
 553     return;
 554   }
 555   ObjectMonitorHandle omh;
 556   inflate(&omh, THREAD, obj(), inflate_cause_notify);
 557   omh.om_ptr()->notifyAll(THREAD);
 558 }
 559 
 560 // -----------------------------------------------------------------------------
 561 // Hash Code handling
 562 //
 563 // Performance concern:
 564 // OrderAccess::storestore() calls release() which at one time stored 0
 565 // into the global volatile OrderAccess::dummy variable. This store was
 566 // unnecessary for correctness. Many threads storing into a common location
 567 // causes considerable cache migration or "sloshing" on large SMP systems.
 568 // As such, I avoided using OrderAccess::storestore(). In some cases
 569 // OrderAccess::fence() -- which incurs local latency on the executing
 570 // processor -- is a better choice as it scales on SMP systems.
 571 //
 572 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for
 573 // a discussion of coherency costs. Note that all our current reference
 574 // platforms provide strong ST-ST order, so the issue is moot on IA32,
 575 // x64, and SPARC.
 576 //
 577 // As a general policy we use "volatile" to control compiler-based reordering


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

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


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


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


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


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

1434 }
1435 
1436 void ObjectSynchronizer::inflate(ObjectMonitorHandle * omh_p, Thread * Self,
1437                                  oop object, const InflateCause cause) {

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


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


1898     if (obj != NULL && deflate_monitor(mid, obj, freeHeadp, freeTailp)) {
1899       // if deflate_monitor succeeded,
1900       // extract from per-thread in-use list
1901       if (mid == *listHeadp) {
1902         *listHeadp = mid->FreeNext;
1903       } else if (cur_mid_in_use != NULL) {
1904         cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1905       }
1906       next = mid->FreeNext;
1907       mid->FreeNext = NULL;  // This mid is current tail in the freeHeadp list
1908       mid = next;
1909       deflated_count++;
1910     } else {
1911       cur_mid_in_use = mid;
1912       mid = mid->FreeNext;
1913     }
1914   }
1915   return deflated_count;
1916 }
1917 
1918 // Walk a given ObjectMonitor list and deflate idle ObjectMonitors using
1919 // a JavaThread. Returns the number of deflated ObjectMonitors. The given
1920 // list could be a per-thread in-use list or the global in-use list.
1921 // Caller acquires gListLock as appropriate. If a safepoint has started,
1922 // then we save state via savedMidInUsep and return to the caller to
1923 // honor the safepoint.
1924 //
1925 int ObjectSynchronizer::deflate_monitor_list_using_JT(ObjectMonitor** listHeadp,
1926                                                       ObjectMonitor** freeHeadp,
1927                                                       ObjectMonitor** freeTailp,
1928                                                       ObjectMonitor** savedMidInUsep) {
1929   assert(AsyncDeflateIdleMonitors, "sanity check");
1930   assert(Thread::current()->is_Java_thread(), "precondition");
1931 
1932   ObjectMonitor* mid;
1933   ObjectMonitor* next;
1934   ObjectMonitor* cur_mid_in_use = NULL;
1935   int deflated_count = 0;
1936 
1937   if (*savedMidInUsep == NULL) {
1938     // No saved state so start at the beginning.
1939     mid = *listHeadp;
1940   } else {
1941     // We're restarting after a safepoint so restore the necessary state
1942     // before we resume.
1943     cur_mid_in_use = *savedMidInUsep;
1944     mid = cur_mid_in_use->FreeNext;
1945   }
1946   while (mid != NULL) {
1947     // Only try to deflate if there is an associated Java object and if
1948     // mid is old (is not newly allocated and is not newly freed).
1949     if (mid->object() != NULL && mid->is_old() &&
1950         deflate_monitor_using_JT(mid, freeHeadp, freeTailp)) {
1951       // Deflation succeeded so update the in-use list.
1952       if (mid == *listHeadp) {
1953         *listHeadp = mid->FreeNext;
1954       } else if (cur_mid_in_use != NULL) {
1955         // Maintain the current in-use list.
1956         cur_mid_in_use->FreeNext = mid->FreeNext;
1957       }
1958       next = mid->FreeNext;
1959       mid->FreeNext = NULL;
1960       // At this point mid is disconnected from the in-use list
1961       // and is the current tail in the freeHeadp list.
1962       mid = next;
1963       deflated_count++;
1964     } else {
1965       // mid is considered in-use if it does not have an associated
1966       // Java object or mid is not old or deflation did not succeed.
1967       // A mid->is_new() node can be seen here when it is freshly returned
1968       // by omAlloc() (and skips the deflation code path).
1969       // A mid->is_old() node can be seen here when deflation failed.
1970       // A mid->is_free() node can be seen here when a fresh node from
1971       // omAlloc() is released by omRelease() due to losing the race
1972       // in inflate().
1973 
1974       if (mid->object() != NULL && mid->is_new()) {
1975         // mid has an associated Java object and has now been seen
1976         // as newly allocated so mark it as "old".
1977         mid->set_allocation_state(ObjectMonitor::Old);
1978       }
1979       cur_mid_in_use = mid;
1980       mid = mid->FreeNext;
1981 
1982       if (SafepointSynchronize::is_synchronizing() &&
1983           cur_mid_in_use != *listHeadp && cur_mid_in_use->is_old()) {
1984         // If a safepoint has started and cur_mid_in_use is not the list
1985         // head and is old, then it is safe to use as saved state. Return
1986         // to the caller so gListLock can be dropped as appropriate
1987         // before blocking.
1988         *savedMidInUsep = cur_mid_in_use;
1989         return deflated_count;
1990       }
1991     }
1992   }
1993   // We finished the list without a safepoint starting so there's
1994   // no need to save state.
1995   *savedMidInUsep = NULL;
1996   return deflated_count;
1997 }
1998 
1999 void ObjectSynchronizer::prepare_deflate_idle_monitors(DeflateMonitorCounters* counters) {
2000   counters->nInuse = 0;              // currently associated with objects
2001   counters->nInCirculation = 0;      // extant
2002   counters->nScavenged = 0;          // reclaimed (global and per-thread)
2003   counters->perThreadScavenged = 0;  // per-thread scavenge total
2004   counters->perThreadTimes = 0.0;    // per-thread scavenge times
2005 }
2006 
2007 void ObjectSynchronizer::deflate_idle_monitors(DeflateMonitorCounters* counters) {
2008   assert(!AsyncDeflateIdleMonitors, "sanity check");
2009   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2010   bool deflated = false;
2011 
2012   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged monitors
2013   ObjectMonitor * freeTailp = NULL;
2014   elapsedTimer timer;
2015 
2016   if (log_is_enabled(Info, monitorinflation)) {
2017     timer.start();
2018   }
2019 
2020   // Prevent omFlush from changing mids in Thread dtor's during deflation
2021   // And in case the vm thread is acquiring a lock during a safepoint
2022   // See e.g. 6320749
2023   Thread::muxAcquire(&gListLock, "deflate_idle_monitors");
2024 
2025   // Note: the thread-local monitors lists get deflated in
2026   // a separate pass. See deflate_thread_local_monitors().
2027 
2028   // For moribund threads, scan gOmInUseList


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




2240   GVars.stwRandom = os::random();
2241   GVars.stwCycle++;
2242   if (needs_special_cleanup) {
2243     set_is_cleanup_requested(false);  // special clean up is done
2244   }
2245 }
2246 
2247 void ObjectSynchronizer::deflate_thread_local_monitors(Thread* thread, DeflateMonitorCounters* counters) {
2248   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2249 
2250   if (AsyncDeflateIdleMonitors) {
2251     // Nothing to do when idle ObjectMonitors are deflated using a
2252     // JavaThread unless a special cleanup has been requested.
2253     if (!is_cleanup_requested()) {
2254       return;
2255     }
2256   }
2257 
2258   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged monitors
2259   ObjectMonitor * freeTailp = NULL;
2260   elapsedTimer timer;
2261 
2262   if (log_is_enabled(Info, safepoint, cleanup) ||
2263       log_is_enabled(Info, monitorinflation)) {
2264     timer.start();
2265   }
2266 
2267   int deflated_count = deflate_monitor_list(thread->omInUseList_addr(), &freeHeadp, &freeTailp);
2268 
2269   Thread::muxAcquire(&gListLock, "deflate_thread_local_monitors(1)");
2270 
2271   // Adjust counters
2272   counters->nInCirculation += thread->omInUseCount;
2273   thread->omInUseCount -= deflated_count;
2274   counters->nScavenged += deflated_count;
2275   counters->nInuse += thread->omInUseCount;
2276   counters->perThreadScavenged += deflated_count;
2277 


2449   } else {
2450     log_error(monitorinflation)("found monitor list errors: error_cnt=%d", error_cnt);
2451   }
2452 
2453   if ((on_exit && log_is_enabled(Info, monitorinflation)) ||
2454       (!on_exit && log_is_enabled(Trace, monitorinflation))) {
2455     // When exiting this log output is at the Info level. When called
2456     // at a safepoint, this log output is at the Trace level since
2457     // there can be a lot of it.
2458     log_in_use_monitor_details(ls, on_exit);
2459   }
2460 
2461   ls->flush();
2462 
2463   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
2464 }
2465 
2466 // Check a free monitor entry; log any errors.
2467 void ObjectSynchronizer::chk_free_entry(JavaThread * jt, ObjectMonitor * n,
2468                                         outputStream * out, int *error_cnt_p) {
2469   if ((!AsyncDeflateIdleMonitors && n->is_busy()) ||
2470       (AsyncDeflateIdleMonitors && n->is_busy_async())) {
2471     if (jt != NULL) {
2472       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2473                     ": free per-thread monitor must not be busy.", p2i(jt),
2474                     p2i(n));
2475     } else {
2476       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2477                     "must not be busy.", p2i(n));
2478     }
2479     *error_cnt_p = *error_cnt_p + 1;
2480   }
2481   if (n->header() != NULL) {
2482     if (jt != NULL) {
2483       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2484                     ": free per-thread monitor must have NULL _header "
2485                     "field: _header=" INTPTR_FORMAT, p2i(jt), p2i(n),
2486                     p2i(n->header()));
2487     } else {
2488       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2489                     "must have NULL _header field: _header=" INTPTR_FORMAT,
2490                     p2i(n), p2i(n->header()));


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


< prev index next >