108 #endif // ndef DTRACE_ENABLED
109
110 // This exists only as a workaround of dtrace bug 6254741
111 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
112 DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
113 return 0;
114 }
115
116 #define NINFLATIONLOCKS 256
117 static volatile intptr_t gInflationLocks[NINFLATIONLOCKS];
118
119 // global list of blocks of monitors
120 PaddedEnd<ObjectMonitor> * volatile ObjectSynchronizer::gBlockList = NULL;
121 // global monitor free list
122 ObjectMonitor * volatile ObjectSynchronizer::gFreeList = NULL;
123 // global monitor in-use list, for moribund threads,
124 // monitors they inflated need to be scanned for deflation
125 ObjectMonitor * volatile ObjectSynchronizer::gOmInUseList = NULL;
126 // count of entries in gOmInUseList
127 int ObjectSynchronizer::gOmInUseCount = 0;
128
129 static volatile intptr_t gListLock = 0; // protects global monitor lists
130 static volatile int gMonitorFreeCount = 0; // # on gFreeList
131 static volatile int gMonitorPopulation = 0; // # Extant -- in circulation
132
133 #define CHAINMARKER (cast_to_oop<intptr_t>(-1))
134
135
136 // =====================> Quick functions
137
138 // The quick_* forms are special fast-path variants used to improve
139 // performance. In the simplest case, a "quick_*" implementation could
140 // simply return false, in which case the caller will perform the necessary
141 // state transitions and call the slow-path form.
142 // The fast-path is designed to handle frequently arising cases in an efficient
143 // manner and is just a degenerate "optimistic" variant of the slow-path.
144 // returns true -- to indicate the call was satisfied.
145 // returns false -- to indicate the call needs the services of the slow-path.
146 // A no-loitering ordinance is in effect for code in the quick_* family
147 // operators: safepoints or indefinite blocking (blocking that might span a
194 }
195
196 // biased locking and any other IMS exception states take the slow-path
197 return false;
198 }
199
200
201 // The LockNode emitted directly at the synchronization site would have
202 // been too big if it were to have included support for the cases of inflated
203 // recursive enter and exit, so they go here instead.
204 // Note that we can't safely call AsyncPrintJavaStack() from within
205 // quick_enter() as our thread state remains _in_Java.
206
207 bool ObjectSynchronizer::quick_enter(oop obj, Thread * Self,
208 BasicLock * lock) {
209 assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
210 assert(Self->is_Java_thread(), "invariant");
211 assert(((JavaThread *) Self)->thread_state() == _thread_in_Java, "invariant");
212 NoSafepointVerifier nsv;
213 if (obj == NULL) return false; // Need to throw NPE
214 const markOop mark = obj->mark();
215
216 if (mark->has_monitor()) {
217 ObjectMonitor * const m = mark->monitor();
218 assert(oopDesc::equals((oop) m->object(), obj), "invariant");
219 Thread * const owner = (Thread *) m->_owner;
220
221 // Lock contention and Transactional Lock Elision (TLE) diagnostics
222 // and observability
223 // Case: light contention possibly amenable to TLE
224 // Case: TLE inimical operations such as nested/recursive synchronization
225
226 if (owner == Self) {
227 m->_recursions++;
228 return true;
229 }
230
231 // This Java Monitor is inflated so obj's header will never be
232 // displaced to this thread's BasicLock. Make the displaced header
233 // non-NULL so this BasicLock is not seen as recursive nor as
234 // being locked. We do this unconditionally so that this thread's
235 // BasicLock cannot be mis-interpreted by any stack walkers. For
236 // performance reasons, stack walkers generally first check for
237 // Biased Locking in the object's header, the second check is for
238 // stack-locking in the object's header, the third check is for
239 // recursive stack-locking in the displaced header in the BasicLock,
240 // and last are the inflated Java Monitor (ObjectMonitor) checks.
241 lock->set_displaced_header(markOopDesc::unused_mark());
242
243 if (owner == NULL && Atomic::replace_if_null(Self, &(m->_owner))) {
244 assert(m->_recursions == 0, "invariant");
245 assert(m->_owner == Self, "invariant");
246 return true;
247 }
248 }
249
250 // Note that we could inflate in quick_enter.
251 // This is likely a useful optimization
252 // Critically, in quick_enter() we must not:
253 // -- perform bias revocation, or
254 // -- block indefinitely, or
255 // -- reach a safepoint
256
257 return false; // revert to slow-path
258 }
259
260 // -----------------------------------------------------------------------------
261 // Fast Monitor Enter/Exit
262 // This the fast monitor enter. The interpreter and compiler use
263 // some assembly copies of this code. Make sure update those code
264 // if the following function is changed. The implementation is
265 // extremely sensitive to race condition. Be careful.
266
267 void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock,
268 bool attempt_rebias, TRAPS) {
311 // does not own the Java Monitor.
312 ObjectMonitor * m = mark->monitor();
313 assert(((oop)(m->object()))->mark() == mark, "invariant");
314 assert(m->is_entered(THREAD), "invariant");
315 }
316 }
317 #endif
318 return;
319 }
320
321 if (mark == (markOop) lock) {
322 // If the object is stack-locked by the current thread, try to
323 // swing the displaced header from the BasicLock back to the mark.
324 assert(dhw->is_neutral(), "invariant");
325 if (object->cas_set_mark(dhw, mark) == mark) {
326 return;
327 }
328 }
329
330 // We have to take the slow-path of possible inflation and then exit.
331 inflate(THREAD, object, inflate_cause_vm_internal)->exit(true, THREAD);
332 }
333
334 // -----------------------------------------------------------------------------
335 // Interpreter/Compiler Slow Case
336 // This routine is used to handle interpreter/compiler slow case
337 // We don't need to use fast path here, because it must have been
338 // failed in the interpreter/compiler code.
339 void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) {
340 markOop mark = obj->mark();
341 assert(!mark->has_bias_pattern(), "should not see bias pattern here");
342
343 if (mark->is_neutral()) {
344 // Anticipate successful CAS -- the ST of the displaced mark must
345 // be visible <= the ST performed by the CAS.
346 lock->set_displaced_header(mark);
347 if (mark == obj()->cas_set_mark((markOop) lock, mark)) {
348 return;
349 }
350 // Fall through to inflate() ...
351 } else if (mark->has_locker() &&
352 THREAD->is_lock_owned((address)mark->locker())) {
353 assert(lock != mark->locker(), "must not re-lock the same lock");
354 assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock");
355 lock->set_displaced_header(NULL);
356 return;
357 }
358
359 // The object header will never be displaced to this lock,
360 // so it does not matter what the value is, except that it
361 // must be non-zero to avoid looking like a re-entrant lock,
362 // and must not look locked either.
363 lock->set_displaced_header(markOopDesc::unused_mark());
364 inflate(THREAD, obj(), inflate_cause_monitor_enter)->enter(THREAD);
365 }
366
367 // This routine is used to handle interpreter/compiler slow case
368 // We don't need to use fast path here, because it must have
369 // failed in the interpreter/compiler code. Simply use the heavy
370 // weight monitor should be ok, unless someone find otherwise.
371 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
372 fast_exit(object, lock, THREAD);
373 }
374
375 // -----------------------------------------------------------------------------
376 // Class Loader support to workaround deadlocks on the class loader lock objects
377 // Also used by GC
378 // complete_exit()/reenter() are used to wait on a nested lock
379 // i.e. to give up an outer lock completely and then re-enter
380 // Used when holding nested locks - lock acquisition order: lock1 then lock2
381 // 1) complete_exit lock1 - saving recursion count
382 // 2) wait on lock2
383 // 3) when notified on lock2, unlock lock2
384 // 4) reenter lock1 with original recursion count
385 // 5) lock lock2
386 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
387 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) {
388 if (UseBiasedLocking) {
389 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
390 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
391 }
392
393 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_vm_internal);
394
395 return monitor->complete_exit(THREAD);
396 }
397
398 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
399 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) {
400 if (UseBiasedLocking) {
401 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
402 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
403 }
404
405 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_vm_internal);
406
407 monitor->reenter(recursion, THREAD);
408 }
409 // -----------------------------------------------------------------------------
410 // JNI locks on java objects
411 // NOTE: must use heavy weight monitor to handle jni monitor enter
412 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) {
413 // the current locking is from JNI instead of Java code
414 if (UseBiasedLocking) {
415 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
416 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
417 }
418 THREAD->set_current_pending_monitor_is_from_java(false);
419 inflate(THREAD, obj(), inflate_cause_jni_enter)->enter(THREAD);
420 THREAD->set_current_pending_monitor_is_from_java(true);
421 }
422
423 // NOTE: must use heavy weight monitor to handle jni monitor exit
424 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
425 if (UseBiasedLocking) {
426 Handle h_obj(THREAD, obj);
427 BiasedLocking::revoke_and_rebias(h_obj, false, THREAD);
428 obj = h_obj();
429 }
430 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
431
432 ObjectMonitor* monitor = inflate(THREAD, obj, inflate_cause_jni_exit);
433 // If this thread has locked the object, exit the monitor. Note: can't use
434 // monitor->check(CHECK); must exit even if an exception is pending.
435 if (monitor->check(THREAD)) {
436 monitor->exit(true, THREAD);
437 }
438 }
439
440 // -----------------------------------------------------------------------------
441 // Internal VM locks on java objects
442 // standard constructor, allows locking failures
443 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) {
444 _dolock = doLock;
445 _thread = thread;
446 debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);)
447 _obj = obj;
448
449 if (_dolock) {
450 ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread);
451 }
452 }
453
454 ObjectLocker::~ObjectLocker() {
455 if (_dolock) {
456 ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread);
457 }
458 }
459
460
461 // -----------------------------------------------------------------------------
462 // Wait/Notify/NotifyAll
463 // NOTE: must use heavy weight monitor to handle wait()
464 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
465 if (UseBiasedLocking) {
466 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
467 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
468 }
469 if (millis < 0) {
470 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
471 }
472 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_wait);
473
474 DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);
475 monitor->wait(millis, true, THREAD);
476
477 // This dummy call is in place to get around dtrace bug 6254741. Once
478 // that's fixed we can uncomment the following line, remove the call
479 // and change this function back into a "void" func.
480 // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
481 return dtrace_waited_probe(monitor, obj, THREAD);
482 }
483
484 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) {
485 if (UseBiasedLocking) {
486 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
487 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
488 }
489 if (millis < 0) {
490 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
491 }
492 inflate(THREAD, obj(), inflate_cause_wait)->wait(millis, false, THREAD);
493 }
494
495 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
496 if (UseBiasedLocking) {
497 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
498 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
499 }
500
501 markOop mark = obj->mark();
502 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
503 return;
504 }
505 inflate(THREAD, obj(), inflate_cause_notify)->notify(THREAD);
506 }
507
508 // NOTE: see comment of notify()
509 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
510 if (UseBiasedLocking) {
511 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
512 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
513 }
514
515 markOop mark = obj->mark();
516 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
517 return;
518 }
519 inflate(THREAD, obj(), inflate_cause_notify)->notifyAll(THREAD);
520 }
521
522 // -----------------------------------------------------------------------------
523 // Hash Code handling
524 //
525 // Performance concern:
526 // OrderAccess::storestore() calls release() which at one time stored 0
527 // into the global volatile OrderAccess::dummy variable. This store was
528 // unnecessary for correctness. Many threads storing into a common location
529 // causes considerable cache migration or "sloshing" on large SMP systems.
530 // As such, I avoided using OrderAccess::storestore(). In some cases
531 // OrderAccess::fence() -- which incurs local latency on the executing
532 // processor -- is a better choice as it scales on SMP systems.
533 //
534 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for
535 // a discussion of coherency costs. Note that all our current reference
536 // platforms provide strong ST-ST order, so the issue is moot on IA32,
537 // x64, and SPARC.
538 //
539 // As a general policy we use "volatile" to control compiler-based reordering
693 Handle hobj(Self, obj);
694 // Relaxing assertion for bug 6320749.
695 assert(Universe::verify_in_progress() ||
696 !SafepointSynchronize::is_at_safepoint(),
697 "biases should not be seen by VM thread here");
698 BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
699 obj = hobj();
700 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
701 }
702 }
703
704 // hashCode() is a heap mutator ...
705 // Relaxing assertion for bug 6320749.
706 assert(Universe::verify_in_progress() || DumpSharedSpaces ||
707 !SafepointSynchronize::is_at_safepoint(), "invariant");
708 assert(Universe::verify_in_progress() || DumpSharedSpaces ||
709 Self->is_Java_thread() , "invariant");
710 assert(Universe::verify_in_progress() || DumpSharedSpaces ||
711 ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant");
712
713 ObjectMonitor* monitor = NULL;
714 markOop temp, test;
715 intptr_t hash;
716 markOop mark = ReadStableMark(obj);
717
718 // object should remain ineligible for biased locking
719 assert(!mark->has_bias_pattern(), "invariant");
720
721 if (mark->is_neutral()) {
722 hash = mark->hash(); // this is a normal header
723 if (hash != 0) { // if it has hash, just return it
724 return hash;
725 }
726 hash = get_next_hash(Self, obj); // allocate a new hash code
727 temp = mark->copy_set_hash(hash); // merge the hash code into header
728 // use (machine word version) atomic operation to install the hash
729 test = obj->cas_set_mark(temp, mark);
730 if (test == mark) {
731 return hash;
732 }
733 // If atomic operation failed, we must inflate the header
734 // into heavy weight monitor. We could add more code here
735 // for fast path, but it does not worth the complexity.
736 } else if (mark->has_monitor()) {
737 monitor = mark->monitor();
738 temp = monitor->header();
739 assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
740 hash = temp->hash();
741 if (hash != 0) {
742 return hash;
743 }
744 // Skip to the following code to reduce code size
745 } else if (Self->is_lock_owned((address)mark->locker())) {
746 temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
747 assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
748 hash = temp->hash(); // by current thread, check if the displaced
749 if (hash != 0) { // header contains hash code
750 return hash;
751 }
752 // WARNING:
753 // The displaced header in the BasicLock on a thread's stack
754 // is strictly immutable. It CANNOT be changed in ANY cases.
755 // So we have to inflate the stack lock into an ObjectMonitor
756 // even if the current thread owns the lock. The BasicLock on
757 // a thread's stack can be asynchronously read by other threads
758 // during an inflate() call so any change to that stack memory
759 // may not propagate to other threads 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(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(temp));
772 test = Atomic::cmpxchg(temp, monitor->header_addr(), mark);
773 if (test != mark) {
774 // The only update to the ObjectMonitor's header/dmw field
775 // is to merge in the hash code. If someone adds a new usage
776 // of the header/dmw field, please update this code.
777 hash = test->hash();
778 assert(test->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(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;
936 int monitor_usage = (monitors_used * 100LL) / gMonitorPopulation;
937 return monitor_usage > MonitorUsedDeflationThreshold;
938 }
939
940 bool ObjectSynchronizer::is_cleanup_needed() {
941 if (MonitorUsedDeflationThreshold > 0) {
942 return monitors_used_above_threshold();
943 }
944 return false;
945 }
946
947 void ObjectSynchronizer::oops_do(OopClosure* f) {
948 // We only scan the global used list here (for moribund threads), and
949 // the thread-local monitors in Thread::oops_do().
950 global_used_oops_do(f);
951 }
952
953 void ObjectSynchronizer::global_used_oops_do(OopClosure* f) {
954 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
955 list_oops_do(gOmInUseList, f);
956 }
957
958 void ObjectSynchronizer::thread_local_used_oops_do(Thread* thread, OopClosure* f) {
959 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
960 list_oops_do(thread->omInUseList, f);
961 }
962
963 void ObjectSynchronizer::list_oops_do(ObjectMonitor* list, OopClosure* f) {
964 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
965 ObjectMonitor* mid;
966 for (mid = list; mid != NULL; mid = mid->FreeNext) {
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(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
1404 // value from the basiclock on the owner's stack to the objectMonitor, all
1405 // the while preserving the hashCode stability invariants. If the owner
1406 // decides to release the lock while the value is 0, the unlock will fail
1407 // and control will eventually pass from slow_exit() to inflate. The owner
1408 // will then spin, waiting for the 0 value to disappear. Put another way,
1409 // the 0 causes the owner to stall if the owner happens to try to
1410 // drop the lock (restoring the header from the basiclock to the object)
1411 // while inflation is in-progress. This protocol avoids races that might
1412 // would otherwise permit hashCode values to change or "flicker" for an object.
1413 // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
1414 // 0 serves as a "BUSY" inflate-in-progress indicator.
1415
1416
1417 // fetch the displaced mark from the owner's stack.
1418 // The owner can't die or unwind past the lock while our INFLATING
1419 // object is in the mark. Furthermore the owner can't complete
1420 // an unlock on the object, either.
1421 markOop dmw = mark->displaced_mark_helper();
1422 // Catch if the object's header is not neutral (not locked and
1423 // not marked is what we care about here).
1424 assert(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1425
1426 // Setup monitor fields to proper values -- prepare the monitor
1427 m->set_header(dmw);
1428
1429 // Optimization: if the mark->locker stack address is associated
1430 // with this thread we could simply set m->_owner = Self.
1431 // Note that a thread can inflate an object
1432 // that it has stack-locked -- as might happen in wait() -- directly
1433 // with CAS. That is, we can avoid the xchg-NULL .... ST idiom.
1434 m->set_owner(mark->locker());
1435 m->set_object(object);
1436 // TODO-FIXME: assert BasicLock->dhw != 0.
1437
1438 // Must preserve store ordering. The monitor state must
1439 // be stable at the time of publishing the monitor address.
1440 guarantee(object->mark() == markOopDesc::INFLATING(), "invariant");
1441 object->release_set_mark(markOopDesc::encode(m));
1442
1443 // Hopefully the performance counters are allocated on distinct cache lines
1444 // to avoid false sharing on MP systems ...
1445 OM_PERFDATA_OP(Inflations, inc());
1446 if (log_is_enabled(Trace, monitorinflation)) {
1447 ResourceMark rm(Self);
1448 lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark="
1449 INTPTR_FORMAT ", type='%s'", p2i(object),
1450 p2i(object->mark()), object->klass()->external_name());
1451 }
1452 if (event.should_commit()) {
1453 post_monitor_inflate_event(&event, object, cause);
1454 }
1455 return m;
1456 }
1457
1458 // CASE: neutral
1459 // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1460 // If we know we're inflating for entry it's better to inflate by swinging a
1461 // pre-locked objectMonitor pointer into the object header. A successful
1462 // CAS inflates the object *and* confers ownership to the inflating thread.
1463 // In the current implementation we use a 2-step mechanism where we CAS()
1464 // to inflate and then CAS() again to try to swing _owner from NULL to Self.
1465 // An inflateTry() method that we could call from fast_enter() and slow_enter()
1466 // would be useful.
1467
1468 // Catch if the object's header is not neutral (not locked and
1469 // not marked is what we care about here).
1470 assert(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark));
1471 ObjectMonitor * m = omAlloc(Self);
1472 // prepare m for installation - set monitor to initial state
1473 m->Recycle();
1474 m->set_header(mark);
1475 m->set_owner(NULL);
1476 m->set_object(object);
1477 m->_recursions = 0;
1478 m->_Responsible = NULL;
1479 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // consider: keep metastats by type/class
1480
1481 if (object->cas_set_mark(markOopDesc::encode(m), mark) != mark) {
1482 m->set_header(NULL);
1483 m->set_object(NULL);
1484 m->Recycle();
1485 omRelease(Self, m, true);
1486 m = NULL;
1487 continue;
1488 // interference - the markword changed - just retry.
1489 // The state-transitions are one-way, so there's no chance of
1490 // live-lock -- "Inflated" is an absorbing state.
1491 }
1492
1493 // Hopefully the performance counters are allocated on distinct
1494 // cache lines to avoid false sharing on MP systems ...
1495 OM_PERFDATA_OP(Inflations, inc());
1496 if (log_is_enabled(Trace, monitorinflation)) {
1497 ResourceMark rm(Self);
1498 lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark="
1499 INTPTR_FORMAT ", type='%s'", p2i(object),
1500 p2i(object->mark()), object->klass()->external_name());
1501 }
1502 if (event.should_commit()) {
1503 post_monitor_inflate_event(&event, object, cause);
1504 }
1505 return m;
1506 }
1507 }
1508
1509
1510 // We maintain a list of in-use monitors for each thread.
1511 //
1512 // deflate_thread_local_monitors() scans a single thread's in-use list, while
1513 // deflate_idle_monitors() scans only a global list of in-use monitors which
1514 // is populated only as a thread dies (see omFlush()).
1515 //
1516 // These operations are called at all safepoints, immediately after mutators
1517 // are stopped, but before any objects have moved. Collectively they traverse
1518 // the population of in-use monitors, deflating where possible. The scavenged
1519 // monitors are returned to the global monitor free list.
1520 //
1521 // Beware that we scavenge at *every* stop-the-world point. Having a large
1522 // number of monitors in-use could negatively impact performance. We also want
1523 // to minimize the total # of monitors in circulation, as they incur a small
1524 // footprint penalty.
1525 //
1526 // Perversely, the heap size -- and thus the STW safepoint rate --
1527 // typically drives the scavenge rate. Large heaps can mean infrequent GC,
1528 // which in turn can mean large(r) numbers of ObjectMonitors in circulation.
1529 // This is an unfortunate aspect of this design.
1530
1531 // Deflate a single monitor if not in-use
1532 // Return true if deflated, false if in-use
1533 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
1534 ObjectMonitor** freeHeadp,
1535 ObjectMonitor** freeTailp) {
1536 bool deflated;
1537 // Normal case ... The monitor is associated with obj.
1538 const markOop mark = obj->mark();
1539 guarantee(mark == markOopDesc::encode(mid), "should match: mark="
1540 INTPTR_FORMAT ", encoded mid=" INTPTR_FORMAT, p2i(mark),
1541 p2i(markOopDesc::encode(mid)));
1542 // Make sure that mark->monitor() and markOopDesc::encode() agree:
1543 guarantee(mark->monitor() == mid, "should match: monitor()=" INTPTR_FORMAT
1544 ", mid=" INTPTR_FORMAT, p2i(mark->monitor()), p2i(mid));
1545 const markOop dmw = mid->header();
1546 guarantee(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1547
1548 if (mid->is_busy()) {
1549 deflated = false;
1550 } else {
1551 // Deflate the monitor if it is no longer being used
1552 // It's idle - scavenge and return to the global free list
1553 // plain old deflation ...
1554 if (log_is_enabled(Trace, monitorinflation)) {
1555 ResourceMark rm;
1556 log_trace(monitorinflation)("deflate_monitor: "
1557 "object=" INTPTR_FORMAT ", mark="
1558 INTPTR_FORMAT ", type='%s'", p2i(obj),
1559 p2i(mark), obj->klass()->external_name());
1560 }
1561
1562 // Restore the header back to obj
1563 obj->release_set_mark(dmw);
1564 mid->clear();
1565
1566 assert(mid->object() == NULL, "invariant: object=" INTPTR_FORMAT,
1567 p2i(mid->object()));
1568
1569 // Move the object to the working free list defined by freeHeadp, freeTailp
1570 if (*freeHeadp == NULL) *freeHeadp = mid;
1571 if (*freeTailp != NULL) {
1572 ObjectMonitor * prevtail = *freeTailp;
1573 assert(prevtail->FreeNext == NULL, "cleaned up deflated?");
1574 prevtail->FreeNext = mid;
1575 }
1576 *freeTailp = mid;
1577 deflated = true;
1578 }
1579 return deflated;
1580 }
1581
1582 // Walk a given monitor list, and deflate idle monitors
1583 // The given list could be a per-thread list or a global list
1584 // Caller acquires gListLock as needed.
1585 //
1586 // In the case of parallel processing of thread local monitor lists,
1587 // work is done by Threads::parallel_threads_do() which ensures that
1588 // each Java thread is processed by exactly one worker thread, and
1589 // thus avoid conflicts that would arise when worker threads would
1590 // process the same monitor lists concurrently.
1591 //
1592 // See also ParallelSPCleanupTask and
1593 // SafepointSynchronize::do_cleanup_tasks() in safepoint.cpp and
1594 // Threads::parallel_java_threads_do() in thread.cpp.
1595 int ObjectSynchronizer::deflate_monitor_list(ObjectMonitor** listHeadp,
1596 ObjectMonitor** freeHeadp,
1597 ObjectMonitor** freeTailp) {
1598 ObjectMonitor* mid;
1599 ObjectMonitor* next;
1600 ObjectMonitor* cur_mid_in_use = NULL;
1601 int deflated_count = 0;
1605 if (obj != NULL && deflate_monitor(mid, obj, freeHeadp, freeTailp)) {
1606 // if deflate_monitor succeeded,
1607 // extract from per-thread in-use list
1608 if (mid == *listHeadp) {
1609 *listHeadp = mid->FreeNext;
1610 } else if (cur_mid_in_use != NULL) {
1611 cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1612 }
1613 next = mid->FreeNext;
1614 mid->FreeNext = NULL; // This mid is current tail in the freeHeadp list
1615 mid = next;
1616 deflated_count++;
1617 } else {
1618 cur_mid_in_use = mid;
1619 mid = mid->FreeNext;
1620 }
1621 }
1622 return deflated_count;
1623 }
1624
1625 void ObjectSynchronizer::prepare_deflate_idle_monitors(DeflateMonitorCounters* counters) {
1626 counters->nInuse = 0; // currently associated with objects
1627 counters->nInCirculation = 0; // extant
1628 counters->nScavenged = 0; // reclaimed (global and per-thread)
1629 counters->perThreadScavenged = 0; // per-thread scavenge total
1630 counters->perThreadTimes = 0.0; // per-thread scavenge times
1631 }
1632
1633 void ObjectSynchronizer::deflate_idle_monitors(DeflateMonitorCounters* counters) {
1634 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1635 bool deflated = false;
1636
1637 ObjectMonitor * freeHeadp = NULL; // Local SLL of scavenged monitors
1638 ObjectMonitor * freeTailp = NULL;
1639 elapsedTimer timer;
1640
1641 if (log_is_enabled(Info, monitorinflation)) {
1642 timer.start();
1643 }
1644
1645 // Prevent omFlush from changing mids in Thread dtor's during deflation
1646 // And in case the vm thread is acquiring a lock during a safepoint
1647 // See e.g. 6320749
1648 Thread::muxAcquire(&gListLock, "deflate_idle_monitors");
1649
1650 // Note: the thread-local monitors lists get deflated in
1651 // a separate pass. See deflate_thread_local_monitors().
1652
1653 // For moribund threads, scan gOmInUseList
1654 int deflated_count = 0;
1667 // constant-time list splice - prepend scavenged segment to gFreeList
1668 freeTailp->FreeNext = gFreeList;
1669 gFreeList = freeHeadp;
1670 }
1671 Thread::muxRelease(&gListLock);
1672 timer.stop();
1673
1674 LogStreamHandle(Debug, monitorinflation) lsh_debug;
1675 LogStreamHandle(Info, monitorinflation) lsh_info;
1676 LogStream * ls = NULL;
1677 if (log_is_enabled(Debug, monitorinflation)) {
1678 ls = &lsh_debug;
1679 } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
1680 ls = &lsh_info;
1681 }
1682 if (ls != NULL) {
1683 ls->print_cr("deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count);
1684 }
1685 }
1686
1687 void ObjectSynchronizer::finish_deflate_idle_monitors(DeflateMonitorCounters* counters) {
1688 // Report the cumulative time for deflating each thread's idle
1689 // monitors. Note: if the work is split among more than one
1690 // worker thread, then the reported time will likely be more
1691 // than a beginning to end measurement of the phase.
1692 log_info(safepoint, cleanup)("deflating per-thread idle monitors, %3.7f secs, monitors=%d", counters->perThreadTimes, counters->perThreadScavenged);
1693
1694 gMonitorFreeCount += counters->nScavenged;
1695
1696 if (log_is_enabled(Debug, monitorinflation)) {
1697 // exit_globals()'s call to audit_and_print_stats() is done
1698 // at the Info level.
1699 ObjectSynchronizer::audit_and_print_stats(false /* on_exit */);
1700 } else if (log_is_enabled(Info, monitorinflation)) {
1701 Thread::muxAcquire(&gListLock, "finish_deflate_idle_monitors");
1702 log_info(monitorinflation)("gMonitorPopulation=%d, gOmInUseCount=%d, "
1703 "gMonitorFreeCount=%d", gMonitorPopulation,
1704 gOmInUseCount, gMonitorFreeCount);
1705 Thread::muxRelease(&gListLock);
1706 }
1707
1708 ForceMonitorScavenge = 0; // Reset
1709
1710 OM_PERFDATA_OP(Deflations, inc(counters->nScavenged));
1711 OM_PERFDATA_OP(MonExtant, set_value(counters->nInCirculation));
1712
1713 GVars.stwRandom = os::random();
1714 GVars.stwCycle++;
1715 }
1716
1717 void ObjectSynchronizer::deflate_thread_local_monitors(Thread* thread, DeflateMonitorCounters* counters) {
1718 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1719
1720 ObjectMonitor * freeHeadp = NULL; // Local SLL of scavenged monitors
1721 ObjectMonitor * freeTailp = NULL;
1722 elapsedTimer timer;
1723
1724 if (log_is_enabled(Info, safepoint, cleanup) ||
1725 log_is_enabled(Info, monitorinflation)) {
1726 timer.start();
1727 }
1728
1729 int deflated_count = deflate_monitor_list(thread->omInUseList_addr(), &freeHeadp, &freeTailp);
1730
1731 Thread::muxAcquire(&gListLock, "deflate_thread_local_monitors");
1732
1733 // Adjust counters
1734 counters->nInCirculation += thread->omInUseCount;
1735 thread->omInUseCount -= deflated_count;
1736 counters->nScavenged += deflated_count;
1737 counters->nInuse += thread->omInUseCount;
1738 counters->perThreadScavenged += deflated_count;
1739
1908 } else {
1909 log_error(monitorinflation)("found monitor list errors: error_cnt=%d", error_cnt);
1910 }
1911
1912 if ((on_exit && log_is_enabled(Info, monitorinflation)) ||
1913 (!on_exit && log_is_enabled(Trace, monitorinflation))) {
1914 // When exiting this log output is at the Info level. When called
1915 // at a safepoint, this log output is at the Trace level since
1916 // there can be a lot of it.
1917 log_in_use_monitor_details(ls, on_exit);
1918 }
1919
1920 ls->flush();
1921
1922 guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
1923 }
1924
1925 // Check a free monitor entry; log any errors.
1926 void ObjectSynchronizer::chk_free_entry(JavaThread * jt, ObjectMonitor * n,
1927 outputStream * out, int *error_cnt_p) {
1928 if (n->is_busy()) {
1929 if (jt != NULL) {
1930 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
1931 ": free per-thread monitor must not be busy.", p2i(jt),
1932 p2i(n));
1933 } else {
1934 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
1935 "must not be busy.", p2i(n));
1936 }
1937 *error_cnt_p = *error_cnt_p + 1;
1938 }
1939 if (n->header() != NULL) {
1940 if (jt != NULL) {
1941 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
1942 ": free per-thread monitor must have NULL _header "
1943 "field: _header=" INTPTR_FORMAT, p2i(jt), p2i(n),
1944 p2i(n->header()));
1945 } else {
1946 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
1947 "must have NULL _header field: _header=" INTPTR_FORMAT,
1948 p2i(n), p2i(n->header()));
1949 }
1950 *error_cnt_p = *error_cnt_p + 1;
1951 }
1952 if (n->object() != NULL) {
1953 if (jt != NULL) {
1954 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
1955 ": free per-thread monitor must have NULL _object "
1956 "field: _object=" INTPTR_FORMAT, p2i(jt), p2i(n),
1957 p2i(n->object()));
1958 } else {
1959 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
1960 "must have NULL _object field: _object=" INTPTR_FORMAT,
1961 p2i(n), p2i(n->object()));
1962 }
1963 *error_cnt_p = *error_cnt_p + 1;
1964 }
1965 }
1966
1967 // Check the global free list and count; log the results of the checks.
1968 void ObjectSynchronizer::chk_global_free_list_and_count(outputStream * out,
1969 int *error_cnt_p) {
1970 int chkMonitorFreeCount = 0;
1971 for (ObjectMonitor * n = gFreeList; n != NULL; n = n->FreeNext) {
2097 out->print_cr("ERROR: jt=" INTPTR_FORMAT ": omInUseCount=%d is not "
2098 "equal to chkOmInUseCount=%d", p2i(jt), jt->omInUseCount,
2099 chkOmInUseCount);
2100 *error_cnt_p = *error_cnt_p + 1;
2101 }
2102 }
2103
2104 // Log details about ObjectMonitors on the in-use lists. The 'BHL'
2105 // flags indicate why the entry is in-use, 'object' and 'object type'
2106 // indicate the associated object and its type.
2107 void ObjectSynchronizer::log_in_use_monitor_details(outputStream * out,
2108 bool on_exit) {
2109 if (!on_exit) {
2110 // Not at VM exit so grab the global list lock.
2111 Thread::muxAcquire(&gListLock, "log_in_use_monitor_details");
2112 }
2113
2114 if (gOmInUseCount > 0) {
2115 out->print_cr("In-use global monitor info:");
2116 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2117 out->print_cr("%18s %s %18s %18s",
2118 "monitor", "BHL", "object", "object type");
2119 out->print_cr("================== === ================== ==================");
2120 for (ObjectMonitor * n = gOmInUseList; n != NULL; n = n->FreeNext) {
2121 const oop obj = (oop) n->object();
2122 const markOop mark = n->header();
2123 ResourceMark rm;
2124 out->print_cr(INTPTR_FORMAT " %d%d%d " INTPTR_FORMAT " %s", p2i(n),
2125 n->is_busy() != 0, mark->hash() != 0, n->owner() != NULL,
2126 p2i(obj), obj->klass()->external_name());
2127 }
2128 }
2129
2130 if (!on_exit) {
2131 Thread::muxRelease(&gListLock);
2132 }
2133
2134 out->print_cr("In-use per-thread monitor info:");
2135 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2136 out->print_cr("%18s %18s %s %18s %18s",
2137 "jt", "monitor", "BHL", "object", "object type");
2138 out->print_cr("================== ================== === ================== ==================");
2139 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2140 for (ObjectMonitor * n = jt->omInUseList; n != NULL; n = n->FreeNext) {
2141 const oop obj = (oop) n->object();
2142 const markOop mark = n->header();
2143 ResourceMark rm;
2144 out->print_cr(INTPTR_FORMAT " " INTPTR_FORMAT " %d%d%d " INTPTR_FORMAT
2145 " %s", p2i(jt), p2i(n), n->is_busy() != 0,
2146 mark->hash() != 0, n->owner() != NULL, p2i(obj),
2147 obj->klass()->external_name());
2148 }
2149 }
2150
2151 out->flush();
2152 }
2153
2154 // Log counts for the global and per-thread monitor lists and return
2155 // the population count.
2156 int ObjectSynchronizer::log_monitor_list_counts(outputStream * out) {
2157 int popCount = 0;
2158 out->print_cr("%18s %10s %10s %10s",
2159 "Global Lists:", "InUse", "Free", "Total");
2160 out->print_cr("================== ========== ========== ==========");
2161 out->print_cr("%18s %10d %10d %10d", "",
2162 gOmInUseCount, gMonitorFreeCount, gMonitorPopulation);
2163 popCount += gOmInUseCount + gMonitorFreeCount;
2164
2165 out->print_cr("%18s %10s %10s %10s",
2166 "Per-Thread Lists:", "InUse", "Free", "Provision");
2167 out->print_cr("================== ========== ========== ==========");
|
108 #endif // ndef DTRACE_ENABLED
109
110 // This exists only as a workaround of dtrace bug 6254741
111 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
112 DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
113 return 0;
114 }
115
116 #define NINFLATIONLOCKS 256
117 static volatile intptr_t gInflationLocks[NINFLATIONLOCKS];
118
119 // global list of blocks of monitors
120 PaddedEnd<ObjectMonitor> * volatile ObjectSynchronizer::gBlockList = NULL;
121 // global monitor free list
122 ObjectMonitor * volatile ObjectSynchronizer::gFreeList = NULL;
123 // global monitor in-use list, for moribund threads,
124 // monitors they inflated need to be scanned for deflation
125 ObjectMonitor * volatile ObjectSynchronizer::gOmInUseList = NULL;
126 // count of entries in gOmInUseList
127 int ObjectSynchronizer::gOmInUseCount = 0;
128 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false;
129 bool volatile ObjectSynchronizer::_is_special_deflation_requested = false;
130 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0;
131
132 static volatile intptr_t gListLock = 0; // protects global monitor lists
133 static volatile int gMonitorFreeCount = 0; // # on gFreeList
134 static volatile int gMonitorPopulation = 0; // # Extant -- in circulation
135
136 #define CHAINMARKER (cast_to_oop<intptr_t>(-1))
137
138
139 // =====================> Quick functions
140
141 // The quick_* forms are special fast-path variants used to improve
142 // performance. In the simplest case, a "quick_*" implementation could
143 // simply return false, in which case the caller will perform the necessary
144 // state transitions and call the slow-path form.
145 // The fast-path is designed to handle frequently arising cases in an efficient
146 // manner and is just a degenerate "optimistic" variant of the slow-path.
147 // returns true -- to indicate the call was satisfied.
148 // returns false -- to indicate the call needs the services of the slow-path.
149 // A no-loitering ordinance is in effect for code in the quick_* family
150 // operators: safepoints or indefinite blocking (blocking that might span a
197 }
198
199 // biased locking and any other IMS exception states take the slow-path
200 return false;
201 }
202
203
204 // The LockNode emitted directly at the synchronization site would have
205 // been too big if it were to have included support for the cases of inflated
206 // recursive enter and exit, so they go here instead.
207 // Note that we can't safely call AsyncPrintJavaStack() from within
208 // quick_enter() as our thread state remains _in_Java.
209
210 bool ObjectSynchronizer::quick_enter(oop obj, Thread * Self,
211 BasicLock * lock) {
212 assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
213 assert(Self->is_Java_thread(), "invariant");
214 assert(((JavaThread *) Self)->thread_state() == _thread_in_Java, "invariant");
215 NoSafepointVerifier nsv;
216 if (obj == NULL) return false; // Need to throw NPE
217
218 while (true) {
219 const markOop mark = obj->mark();
220
221 if (mark->has_monitor()) {
222 ObjectMonitorHandle omh;
223 if (!omh.save_om_ptr(obj, mark)) {
224 // Lost a race with async deflation so try again.
225 assert(AsyncDeflateIdleMonitors, "sanity check");
226 continue;
227 }
228 ObjectMonitor * const m = omh.om_ptr();
229 assert(oopDesc::equals((oop) m->object(), obj), "invariant");
230 Thread * const owner = (Thread *) m->_owner;
231
232 // Lock contention and Transactional Lock Elision (TLE) diagnostics
233 // and observability
234 // Case: light contention possibly amenable to TLE
235 // Case: TLE inimical operations such as nested/recursive synchronization
236
237 if (owner == Self) {
238 m->_recursions++;
239 return true;
240 }
241
242 // This Java Monitor is inflated so obj's header will never be
243 // displaced to this thread's BasicLock. Make the displaced header
244 // non-NULL so this BasicLock is not seen as recursive nor as
245 // being locked. We do this unconditionally so that this thread's
246 // BasicLock cannot be mis-interpreted by any stack walkers. For
247 // performance reasons, stack walkers generally first check for
248 // Biased Locking in the object's header, the second check is for
249 // stack-locking in the object's header, the third check is for
250 // recursive stack-locking in the displaced header in the BasicLock,
251 // and last are the inflated Java Monitor (ObjectMonitor) checks.
252 lock->set_displaced_header(markOopDesc::unused_mark());
253
254 if (owner == NULL && Atomic::replace_if_null(Self, &(m->_owner))) {
255 assert(m->_recursions == 0, "invariant");
256 assert(m->_owner == Self, "invariant");
257 return true;
258 }
259 }
260 break;
261 }
262
263 // Note that we could inflate in quick_enter.
264 // This is likely a useful optimization
265 // Critically, in quick_enter() we must not:
266 // -- perform bias revocation, or
267 // -- block indefinitely, or
268 // -- reach a safepoint
269
270 return false; // revert to slow-path
271 }
272
273 // -----------------------------------------------------------------------------
274 // Fast Monitor Enter/Exit
275 // This the fast monitor enter. The interpreter and compiler use
276 // some assembly copies of this code. Make sure update those code
277 // if the following function is changed. The implementation is
278 // extremely sensitive to race condition. Be careful.
279
280 void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock,
281 bool attempt_rebias, TRAPS) {
324 // does not own the Java Monitor.
325 ObjectMonitor * m = mark->monitor();
326 assert(((oop)(m->object()))->mark() == mark, "invariant");
327 assert(m->is_entered(THREAD), "invariant");
328 }
329 }
330 #endif
331 return;
332 }
333
334 if (mark == (markOop) lock) {
335 // If the object is stack-locked by the current thread, try to
336 // swing the displaced header from the BasicLock back to the mark.
337 assert(dhw->is_neutral(), "invariant");
338 if (object->cas_set_mark(dhw, mark) == mark) {
339 return;
340 }
341 }
342
343 // We have to take the slow-path of possible inflation and then exit.
344 ObjectMonitorHandle omh;
345 inflate(&omh, THREAD, object, inflate_cause_vm_internal);
346 omh.om_ptr()->exit(true, THREAD);
347 }
348
349 // -----------------------------------------------------------------------------
350 // Interpreter/Compiler Slow Case
351 // This routine is used to handle interpreter/compiler slow case
352 // We don't need to use fast path here, because it must have been
353 // failed in the interpreter/compiler code.
354 void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) {
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 omh.om_ptr()->enter(THREAD);
382 }
383
384 // This routine is used to handle interpreter/compiler slow case
385 // We don't need to use fast path here, because it must have
386 // failed in the interpreter/compiler code. Simply use the heavy
387 // weight monitor should be ok, unless someone find otherwise.
388 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
389 fast_exit(object, lock, THREAD);
390 }
391
392 // -----------------------------------------------------------------------------
393 // Class Loader support to workaround deadlocks on the class loader lock objects
394 // Also used by GC
395 // complete_exit()/reenter() are used to wait on a nested lock
396 // i.e. to give up an outer lock completely and then re-enter
397 // Used when holding nested locks - lock acquisition order: lock1 then lock2
398 // 1) complete_exit lock1 - saving recursion count
399 // 2) wait on lock2
400 // 3) when notified on lock2, unlock lock2
401 // 4) reenter lock1 with original recursion count
402 // 5) lock lock2
403 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
404 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) {
405 if (UseBiasedLocking) {
406 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
407 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
408 }
409
410 ObjectMonitorHandle omh;
411 inflate(&omh, THREAD, obj(), inflate_cause_vm_internal);
412 intptr_t ret_code = omh.om_ptr()->complete_exit(THREAD);
413 return ret_code;
414 }
415
416 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
417 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) {
418 if (UseBiasedLocking) {
419 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
420 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
421 }
422
423 ObjectMonitorHandle omh;
424 inflate(&omh, THREAD, obj(), inflate_cause_vm_internal);
425 omh.om_ptr()->reenter(recursion, THREAD);
426 }
427 // -----------------------------------------------------------------------------
428 // JNI locks on java objects
429 // NOTE: must use heavy weight monitor to handle jni monitor enter
430 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) {
431 // the current locking is from JNI instead of Java code
432 if (UseBiasedLocking) {
433 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
434 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
435 }
436 THREAD->set_current_pending_monitor_is_from_java(false);
437 ObjectMonitorHandle omh;
438 inflate(&omh, THREAD, obj(), inflate_cause_jni_enter);
439 omh.om_ptr()->enter(THREAD);
440 THREAD->set_current_pending_monitor_is_from_java(true);
441 }
442
443 // NOTE: must use heavy weight monitor to handle jni monitor exit
444 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
445 if (UseBiasedLocking) {
446 Handle h_obj(THREAD, obj);
447 BiasedLocking::revoke_and_rebias(h_obj, false, THREAD);
448 obj = h_obj();
449 }
450 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
451
452 ObjectMonitorHandle omh;
453 inflate(&omh, THREAD, obj, inflate_cause_jni_exit);
454 ObjectMonitor * monitor = omh.om_ptr();
455 // If this thread has locked the object, exit the monitor. Note: can't use
456 // monitor->check(CHECK); must exit even if an exception is pending.
457 if (monitor->check(THREAD)) {
458 monitor->exit(true, THREAD);
459 }
460 }
461
462 // -----------------------------------------------------------------------------
463 // Internal VM locks on java objects
464 // standard constructor, allows locking failures
465 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) {
466 _dolock = doLock;
467 _thread = thread;
468 debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);)
469 _obj = obj;
470
471 if (_dolock) {
472 ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread);
473 }
474 }
475
476 ObjectLocker::~ObjectLocker() {
477 if (_dolock) {
478 ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread);
479 }
480 }
481
482
483 // -----------------------------------------------------------------------------
484 // Wait/Notify/NotifyAll
485 // NOTE: must use heavy weight monitor to handle wait()
486 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
487 if (UseBiasedLocking) {
488 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
489 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
490 }
491 if (millis < 0) {
492 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
493 }
494 ObjectMonitorHandle omh;
495 inflate(&omh, THREAD, obj(), inflate_cause_wait);
496 ObjectMonitor * monitor = omh.om_ptr();
497
498 DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);
499 monitor->wait(millis, true, THREAD);
500
501 // This dummy call is in place to get around dtrace bug 6254741. Once
502 // that's fixed we can uncomment the following line, remove the call
503 // and change this function back into a "void" func.
504 // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
505 int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
506 return ret_code;
507 }
508
509 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) {
510 if (UseBiasedLocking) {
511 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
512 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
513 }
514 if (millis < 0) {
515 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
516 }
517 ObjectMonitorHandle omh;
518 inflate(&omh, THREAD, obj(), inflate_cause_wait);
519 omh.om_ptr()->wait(millis, false, THREAD);
520 }
521
522 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
523 if (UseBiasedLocking) {
524 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
525 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
526 }
527
528 markOop mark = obj->mark();
529 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
530 return;
531 }
532 ObjectMonitorHandle omh;
533 inflate(&omh, THREAD, obj(), inflate_cause_notify);
534 omh.om_ptr()->notify(THREAD);
535 }
536
537 // NOTE: see comment of notify()
538 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
539 if (UseBiasedLocking) {
540 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
541 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
542 }
543
544 markOop mark = obj->mark();
545 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
546 return;
547 }
548 ObjectMonitorHandle omh;
549 inflate(&omh, THREAD, obj(), inflate_cause_notify);
550 omh.om_ptr()->notifyAll(THREAD);
551 }
552
553 // -----------------------------------------------------------------------------
554 // Hash Code handling
555 //
556 // Performance concern:
557 // OrderAccess::storestore() calls release() which at one time stored 0
558 // into the global volatile OrderAccess::dummy variable. This store was
559 // unnecessary for correctness. Many threads storing into a common location
560 // causes considerable cache migration or "sloshing" on large SMP systems.
561 // As such, I avoided using OrderAccess::storestore(). In some cases
562 // OrderAccess::fence() -- which incurs local latency on the executing
563 // processor -- is a better choice as it scales on SMP systems.
564 //
565 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for
566 // a discussion of coherency costs. Note that all our current reference
567 // platforms provide strong ST-ST order, so the issue is moot on IA32,
568 // x64, and SPARC.
569 //
570 // As a general policy we use "volatile" to control compiler-based reordering
724 Handle hobj(Self, obj);
725 // Relaxing assertion for bug 6320749.
726 assert(Universe::verify_in_progress() ||
727 !SafepointSynchronize::is_at_safepoint(),
728 "biases should not be seen by VM thread here");
729 BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
730 obj = hobj();
731 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
732 }
733 }
734
735 // hashCode() is a heap mutator ...
736 // Relaxing assertion for bug 6320749.
737 assert(Universe::verify_in_progress() || DumpSharedSpaces ||
738 !SafepointSynchronize::is_at_safepoint(), "invariant");
739 assert(Universe::verify_in_progress() || DumpSharedSpaces ||
740 Self->is_Java_thread() , "invariant");
741 assert(Universe::verify_in_progress() || DumpSharedSpaces ||
742 ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant");
743
744 while (true) {
745 ObjectMonitor* monitor = NULL;
746 markOop temp, test;
747 intptr_t hash;
748 markOop mark = ReadStableMark(obj);
749
750 // object should remain ineligible for biased locking
751 assert(!mark->has_bias_pattern(), "invariant");
752
753 if (mark->is_neutral()) {
754 hash = mark->hash(); // this is a normal header
755 if (hash != 0) { // if it has hash, just return it
756 return hash;
757 }
758 hash = get_next_hash(Self, obj); // allocate a new hash code
759 temp = mark->copy_set_hash(hash); // merge the hash code into header
760 // use (machine word version) atomic operation to install the hash
761 test = obj->cas_set_mark(temp, mark);
762 if (test == mark) {
763 return hash;
764 }
765 // If atomic operation failed, we must inflate the header
766 // into heavy weight monitor. We could add more code here
767 // for fast path, but it does not worth the complexity.
768 } else if (mark->has_monitor()) {
769 ObjectMonitorHandle omh;
770 if (!omh.save_om_ptr(obj, mark)) {
771 // Lost a race with async deflation so try again.
772 assert(AsyncDeflateIdleMonitors, "sanity check");
773 continue;
774 }
775 monitor = omh.om_ptr();
776 temp = monitor->header();
777 assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
778 hash = temp->hash();
779 if (hash != 0) {
780 return hash;
781 }
782 // Skip to the following code to reduce code size
783 } else if (Self->is_lock_owned((address)mark->locker())) {
784 temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
785 assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
786 hash = temp->hash(); // by current thread, check if the displaced
787 if (hash != 0) { // header contains hash code
788 return hash;
789 }
790 // WARNING:
791 // The displaced header in the BasicLock on a thread's stack
792 // is strictly immutable. It CANNOT be changed in ANY cases.
793 // So we have to inflate the stack lock into an ObjectMonitor
794 // even if the current thread owns the lock. The BasicLock on
795 // a thread's stack can be asynchronously read by other threads
796 // during an inflate() call so any change to that stack memory
797 // may not propagate to other threads correctly.
798 }
799
800 // Inflate the monitor to set hash code
801 ObjectMonitorHandle omh;
802 inflate(&omh, Self, obj, inflate_cause_hash_code);
803 monitor = omh.om_ptr();
804 // Load displaced header and check it has hash code
805 mark = monitor->header();
806 assert(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark));
807 hash = mark->hash();
808 if (hash == 0) {
809 hash = get_next_hash(Self, obj);
810 temp = mark->copy_set_hash(hash); // merge hash code into header
811 assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
812 test = Atomic::cmpxchg(temp, monitor->header_addr(), mark);
813 if (test != mark) {
814 // The only non-deflation update to the ObjectMonitor's
815 // header/dmw field is to merge in the hash code. If someone
816 // adds a new usage of the header/dmw field, please update
817 // this code.
818 // ObjectMonitor::install_displaced_markword_in_object()
819 // does mark the header/dmw field as part of async deflation,
820 // but that protocol cannot happen now due to the
821 // ObjectMonitorHandle above.
822 hash = test->hash();
823 assert(test->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(test));
824 assert(hash != 0, "Trivial unexpected object/monitor header usage.");
825 }
826 }
827 // We finally get the hash
828 return hash;
829 }
830 }
831
832 // Deprecated -- use FastHashCode() instead.
833
834 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
835 return FastHashCode(Thread::current(), obj());
836 }
837
838
839 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread,
840 Handle h_obj) {
841 if (UseBiasedLocking) {
842 BiasedLocking::revoke_and_rebias(h_obj, false, thread);
843 assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
844 }
845
846 assert(thread == JavaThread::current(), "Can only be called on current thread");
847 oop obj = h_obj();
848
849 while (true) {
850 markOop mark = ReadStableMark(obj);
851
852 // Uncontended case, header points to stack
853 if (mark->has_locker()) {
854 return thread->is_lock_owned((address)mark->locker());
855 }
856 // Contended case, header points to ObjectMonitor (tagged pointer)
857 if (mark->has_monitor()) {
858 ObjectMonitorHandle omh;
859 if (!omh.save_om_ptr(obj, mark)) {
860 // Lost a race with async deflation so try again.
861 assert(AsyncDeflateIdleMonitors, "sanity check");
862 continue;
863 }
864 bool ret_code = omh.om_ptr()->is_entered(thread) != 0;
865 return ret_code;
866 }
867 // Unlocked case, header in place
868 assert(mark->is_neutral(), "sanity check");
869 return false;
870 }
871 }
872
873 // Be aware of this method could revoke bias of the lock object.
874 // This method queries the ownership of the lock handle specified by 'h_obj'.
875 // If the current thread owns the lock, it returns owner_self. If no
876 // thread owns the lock, it returns owner_none. Otherwise, it will return
877 // owner_other.
878 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership
879 (JavaThread *self, Handle h_obj) {
880 // The caller must beware this method can revoke bias, and
881 // revocation can result in a safepoint.
882 assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
883 assert(self->thread_state() != _thread_blocked, "invariant");
884
885 // Possible mark states: neutral, biased, stack-locked, inflated
886
887 if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) {
888 // CASE: biased
889 BiasedLocking::revoke_and_rebias(h_obj, false, self);
890 assert(!h_obj->mark()->has_bias_pattern(),
891 "biases should be revoked by now");
892 }
893
894 assert(self == JavaThread::current(), "Can only be called on current thread");
895 oop obj = h_obj();
896
897 while (true) {
898 markOop mark = ReadStableMark(obj);
899
900 // CASE: stack-locked. Mark points to a BasicLock on the owner's stack.
901 if (mark->has_locker()) {
902 return self->is_lock_owned((address)mark->locker()) ?
903 owner_self : owner_other;
904 }
905
906 // CASE: inflated. Mark (tagged pointer) points to an ObjectMonitor.
907 // The Object:ObjectMonitor relationship is stable as long as we're
908 // not at a safepoint and AsyncDeflateIdleMonitors is false.
909 if (mark->has_monitor()) {
910 ObjectMonitorHandle omh;
911 if (!omh.save_om_ptr(obj, mark)) {
912 // Lost a race with async deflation so try again.
913 assert(AsyncDeflateIdleMonitors, "sanity check");
914 continue;
915 }
916 ObjectMonitor * monitor = omh.om_ptr();
917 void * owner = monitor->_owner;
918 if (owner == NULL) return owner_none;
919 return (owner == self ||
920 self->is_lock_owned((address)owner)) ? owner_self : owner_other;
921 }
922
923 // CASE: neutral
924 assert(mark->is_neutral(), "sanity check");
925 return owner_none; // it's unlocked
926 }
927 }
928
929 // FIXME: jvmti should call this
930 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
931 if (UseBiasedLocking) {
932 if (SafepointSynchronize::is_at_safepoint()) {
933 BiasedLocking::revoke_at_safepoint(h_obj);
934 } else {
935 BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current());
936 }
937 assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
938 }
939
940 oop obj = h_obj();
941
942 while (true) {
943 address owner = NULL;
944 markOop mark = ReadStableMark(obj);
945
946 // Uncontended case, header points to stack
947 if (mark->has_locker()) {
948 owner = (address) mark->locker();
949 }
950
951 // Contended case, header points to ObjectMonitor (tagged pointer)
952 else if (mark->has_monitor()) {
953 ObjectMonitorHandle omh;
954 if (!omh.save_om_ptr(obj, mark)) {
955 // Lost a race with async deflation so try again.
956 assert(AsyncDeflateIdleMonitors, "sanity check");
957 continue;
958 }
959 ObjectMonitor* monitor = omh.om_ptr();
960 assert(monitor != NULL, "monitor should be non-null");
961 owner = (address) monitor->owner();
962 }
963
964 if (owner != NULL) {
965 // owning_thread_from_monitor_owner() may also return NULL here
966 return Threads::owning_thread_from_monitor_owner(t_list, owner);
967 }
968
969 // Unlocked case, header in place
970 // Cannot have assertion since this object may have been
971 // locked by another thread when reaching here.
972 // assert(mark->is_neutral(), "sanity check");
973
974 return NULL;
975 }
976 }
977
978 // Visitors ...
979
980 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) {
981 PaddedEnd<ObjectMonitor> * block = OrderAccess::load_acquire(&gBlockList);
982 while (block != NULL) {
983 assert(block->object() == CHAINMARKER, "must be a block header");
984 for (int i = _BLOCKSIZE - 1; i > 0; i--) {
985 ObjectMonitor* mid = (ObjectMonitor *)(block + i);
986 if (mid->is_active()) {
987 ObjectMonitorHandle omh(mid);
988
989 if (mid->object() == NULL ||
990 (AsyncDeflateIdleMonitors && mid->_owner == DEFLATER_MARKER)) {
991 // Only process with closure if the object is set.
992 // For async deflation, race here if monitor is not owned!
993 // The above ref_count bump (in ObjectMonitorHandle ctr)
994 // will cause subsequent async deflation to skip it.
995 // However, previous or concurrent async deflation is a race.
996 continue;
997 }
998 closure->do_monitor(mid);
999 }
1000 }
1001 block = (PaddedEnd<ObjectMonitor> *)block->FreeNext;
1002 }
1003 }
1004
1005 // Get the next block in the block list.
1006 static inline PaddedEnd<ObjectMonitor>* next(PaddedEnd<ObjectMonitor>* block) {
1007 assert(block->object() == CHAINMARKER, "must be a block header");
1008 block = (PaddedEnd<ObjectMonitor>*) block->FreeNext;
1009 assert(block == NULL || block->object() == CHAINMARKER, "must be a block header");
1010 return block;
1011 }
1012
1013 static bool monitors_used_above_threshold() {
1014 if (gMonitorPopulation == 0) {
1015 return false;
1016 }
1017 if (MonitorUsedDeflationThreshold > 0) {
1018 int monitors_used = gMonitorPopulation - gMonitorFreeCount;
1019 int monitor_usage = (monitors_used * 100LL) / gMonitorPopulation;
1020 return monitor_usage > MonitorUsedDeflationThreshold;
1021 }
1022 return false;
1023 }
1024
1025 bool ObjectSynchronizer::is_async_deflation_needed() {
1026 if (!AsyncDeflateIdleMonitors) {
1027 return false;
1028 }
1029 if (is_async_deflation_requested()) {
1030 // Async deflation request.
1031 return true;
1032 }
1033 if (AsyncDeflationInterval > 0 &&
1034 time_since_last_async_deflation_ms() > AsyncDeflationInterval &&
1035 monitors_used_above_threshold()) {
1036 // It's been longer than our specified deflate interval and there
1037 // are too many monitors in use. We don't deflate more frequently
1038 // than AsyncDeflationInterval (unless is_async_deflation_requested)
1039 // in order to not swamp the ServiceThread.
1040 _last_async_deflation_time_ns = os::javaTimeNanos();
1041 return true;
1042 }
1043 return false;
1044 }
1045
1046 bool ObjectSynchronizer::is_safepoint_deflation_needed() {
1047 if (!AsyncDeflateIdleMonitors) {
1048 if (monitors_used_above_threshold()) {
1049 // Too many monitors in use.
1050 return true;
1051 }
1052 return false;
1053 }
1054 if (is_special_deflation_requested()) {
1055 // For AsyncDeflateIdleMonitors only do a safepoint deflation
1056 // if there is a special deflation request.
1057 return true;
1058 }
1059 return false;
1060 }
1061
1062 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() {
1063 return (os::javaTimeNanos() - _last_async_deflation_time_ns) / (NANOUNITS / MILLIUNITS);
1064 }
1065
1066 void ObjectSynchronizer::oops_do(OopClosure* f) {
1067 // We only scan the global used list here (for moribund threads), and
1068 // the thread-local monitors in Thread::oops_do().
1069 global_used_oops_do(f);
1070 }
1071
1072 void ObjectSynchronizer::global_used_oops_do(OopClosure* f) {
1073 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1074 list_oops_do(gOmInUseList, f);
1075 }
1076
1077 void ObjectSynchronizer::thread_local_used_oops_do(Thread* thread, OopClosure* f) {
1078 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1079 list_oops_do(thread->omInUseList, f);
1080 }
1081
1082 void ObjectSynchronizer::list_oops_do(ObjectMonitor* list, OopClosure* f) {
1083 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1084 ObjectMonitor* mid;
1085 for (mid = list; mid != NULL; mid = mid->FreeNext) {
1125 // See also: GuaranteedSafepointInterval
1126 //
1127 // The current implementation uses asynchronous VM operations.
1128
1129 static void InduceScavenge(Thread * Self, const char * Whence) {
1130 // Induce STW safepoint to trim monitors
1131 // Ultimately, this results in a call to deflate_idle_monitors() in the near future.
1132 // More precisely, trigger an asynchronous STW safepoint as the number
1133 // of active monitors passes the specified threshold.
1134 // TODO: assert thread state is reasonable
1135
1136 if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) {
1137 // Induce a 'null' safepoint to scavenge monitors
1138 // Must VM_Operation instance be heap allocated as the op will be enqueue and posted
1139 // to the VMthread and have a lifespan longer than that of this activation record.
1140 // The VMThread will delete the op when completed.
1141 VMThread::execute(new VM_ScavengeMonitors());
1142 }
1143 }
1144
1145 ObjectMonitor* ObjectSynchronizer::omAlloc(Thread * Self,
1146 const InflateCause cause) {
1147 // A large MAXPRIVATE value reduces both list lock contention
1148 // and list coherency traffic, but also tends to increase the
1149 // number of objectMonitors in circulation as well as the STW
1150 // scavenge costs. As usual, we lean toward time in space-time
1151 // tradeoffs.
1152 const int MAXPRIVATE = 1024;
1153
1154 if (AsyncDeflateIdleMonitors) {
1155 JavaThread * jt = (JavaThread *)Self;
1156 if (jt->omShouldDeflateIdleMonitors && jt->omInUseCount > 0 &&
1157 cause != inflate_cause_vm_internal) {
1158 // Deflate any per-thread idle monitors for this JavaThread if
1159 // this is not an internal inflation; internal inflations can
1160 // occur in places where it is not safe to pause for a safepoint.
1161 // Clean up your own mess. (Gibbs Rule 45) Otherwise, skip this
1162 // deflation. deflate_global_idle_monitors_using_JT() is called
1163 // by the ServiceThread.
1164 debug_only(jt->check_for_valid_safepoint_state(false);)
1165 ObjectSynchronizer::deflate_per_thread_idle_monitors_using_JT();
1166 }
1167 }
1168
1169 for (;;) {
1170 ObjectMonitor * m;
1171
1172 // 1: try to allocate from the thread's local omFreeList.
1173 // Threads will attempt to allocate first from their local list, then
1174 // from the global list, and only after those attempts fail will the thread
1175 // attempt to instantiate new monitors. Thread-local free lists take
1176 // heat off the gListLock and improve allocation latency, as well as reducing
1177 // coherency traffic on the shared global list.
1178 m = Self->omFreeList;
1179 if (m != NULL) {
1180 Self->omFreeList = m->FreeNext;
1181 Self->omFreeCount--;
1182 guarantee(m->object() == NULL, "invariant");
1183 m->set_allocation_state(ObjectMonitor::New);
1184 m->FreeNext = Self->omInUseList;
1185 Self->omInUseList = m;
1186 Self->omInUseCount++;
1187 return m;
1188 }
1189
1190 // 2: try to allocate from the global gFreeList
1191 // CONSIDER: use muxTry() instead of muxAcquire().
1192 // If the muxTry() fails then drop immediately into case 3.
1193 // If we're using thread-local free lists then try
1194 // to reprovision the caller's free list.
1195 if (gFreeList != NULL) {
1196 // Reprovision the thread's omFreeList.
1197 // Use bulk transfers to reduce the allocation rate and heat
1198 // on various locks.
1199 Thread::muxAcquire(&gListLock, "omAlloc(1)");
1200 for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL;) {
1201 gMonitorFreeCount--;
1202 ObjectMonitor * take = gFreeList;
1203 gFreeList = take->FreeNext;
1204 guarantee(take->object() == NULL, "invariant");
1205 if (AsyncDeflateIdleMonitors) {
1206 // Clear any values we allowed to linger during async deflation.
1207 take->_header = NULL;
1208 take->set_owner(NULL);
1209
1210 if (take->ref_count() < 0) {
1211 // Add back max_jint to restore the ref_count field to its
1212 // proper value.
1213 Atomic::add(max_jint, &take->_ref_count);
1214
1215 assert(take->ref_count() >= 0, "must not be negative: ref_count=%d",
1216 take->ref_count());
1217 }
1218 }
1219 guarantee(!take->is_busy(), "invariant");
1220 take->Recycle();
1221 assert(take->is_free(), "invariant");
1222 omRelease(Self, take, false);
1223 }
1224 Thread::muxRelease(&gListLock);
1225 Self->omFreeProvision += 1 + (Self->omFreeProvision/2);
1226 if (Self->omFreeProvision > MAXPRIVATE) Self->omFreeProvision = MAXPRIVATE;
1227
1228 const int mx = MonitorBound;
1229 if (mx > 0 && (gMonitorPopulation-gMonitorFreeCount) > mx) {
1230 // We can't safely induce a STW safepoint from omAlloc() as our thread
1231 // state may not be appropriate for such activities and callers may hold
1232 // naked oops, so instead we defer the action.
1233 InduceScavenge(Self, "omAlloc");
1234 }
1235 continue;
1236 }
1237
1238 // 3: allocate a block of new ObjectMonitors
1239 // Both the local and global free lists are empty -- resort to malloc().
1240 // In the current implementation objectMonitors are TSM - immortal.
1241 // Ideally, we'd write "new ObjectMonitor[_BLOCKSIZE], but we want
1254
1255 // NOTE: (almost) no way to recover if allocation failed.
1256 // We might be able to induce a STW safepoint and scavenge enough
1257 // objectMonitors to permit progress.
1258 if (temp == NULL) {
1259 vm_exit_out_of_memory(neededsize, OOM_MALLOC_ERROR,
1260 "Allocate ObjectMonitors");
1261 }
1262 (void)memset((void *) temp, 0, neededsize);
1263
1264 // Format the block.
1265 // initialize the linked list, each monitor points to its next
1266 // forming the single linked free list, the very first monitor
1267 // will points to next block, which forms the block list.
1268 // The trick of using the 1st element in the block as gBlockList
1269 // linkage should be reconsidered. A better implementation would
1270 // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; }
1271
1272 for (int i = 1; i < _BLOCKSIZE; i++) {
1273 temp[i].FreeNext = (ObjectMonitor *)&temp[i+1];
1274 assert(temp[i].is_free(), "invariant");
1275 }
1276
1277 // terminate the last monitor as the end of list
1278 temp[_BLOCKSIZE - 1].FreeNext = NULL;
1279
1280 // Element [0] is reserved for global list linkage
1281 temp[0].set_object(CHAINMARKER);
1282
1283 // Consider carving out this thread's current request from the
1284 // block in hand. This avoids some lock traffic and redundant
1285 // list activity.
1286
1287 // Acquire the gListLock to manipulate gBlockList and gFreeList.
1288 // An Oyama-Taura-Yonezawa scheme might be more efficient.
1289 Thread::muxAcquire(&gListLock, "omAlloc(2)");
1290 gMonitorPopulation += _BLOCKSIZE-1;
1291 gMonitorFreeCount += _BLOCKSIZE-1;
1292
1293 // Add the new block to the list of extant blocks (gBlockList).
1294 // The very first objectMonitor in a block is reserved and dedicated.
1297 // There are lock-free uses of gBlockList so make sure that
1298 // the previous stores happen before we update gBlockList.
1299 OrderAccess::release_store(&gBlockList, temp);
1300
1301 // Add the new string of objectMonitors to the global free list
1302 temp[_BLOCKSIZE - 1].FreeNext = gFreeList;
1303 gFreeList = temp + 1;
1304 Thread::muxRelease(&gListLock);
1305 }
1306 }
1307
1308 // Place "m" on the caller's private per-thread omFreeList.
1309 // In practice there's no need to clamp or limit the number of
1310 // monitors on a thread's omFreeList as the only time we'll call
1311 // omRelease is to return a monitor to the free list after a CAS
1312 // attempt failed. This doesn't allow unbounded #s of monitors to
1313 // accumulate on a thread's free list.
1314 //
1315 // Key constraint: all ObjectMonitors on a thread's free list and the global
1316 // free list must have their object field set to null. This prevents the
1317 // scavenger -- deflate_monitor_list() or deflate_monitor_list_using_JT()
1318 // -- from reclaiming them while we are trying to release them.
1319
1320 void ObjectSynchronizer::omRelease(Thread * Self, ObjectMonitor * m,
1321 bool fromPerThreadAlloc) {
1322 guarantee(m->header() == NULL, "invariant");
1323 guarantee(m->object() == NULL, "invariant");
1324 guarantee(((m->is_busy()|m->_recursions) == 0), "freeing in-use monitor");
1325 m->set_allocation_state(ObjectMonitor::Free);
1326 // Remove from omInUseList
1327 if (fromPerThreadAlloc) {
1328 ObjectMonitor* cur_mid_in_use = NULL;
1329 bool extracted = false;
1330 for (ObjectMonitor* mid = Self->omInUseList; mid != NULL; cur_mid_in_use = mid, mid = mid->FreeNext) {
1331 if (m == mid) {
1332 // extract from per-thread in-use list
1333 if (mid == Self->omInUseList) {
1334 Self->omInUseList = mid->FreeNext;
1335 } else if (cur_mid_in_use != NULL) {
1336 cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1337 }
1338 extracted = true;
1339 Self->omInUseCount--;
1340 break;
1341 }
1342 }
1343 assert(extracted, "Should have extracted from in-use list");
1344 }
1345
1346 // FreeNext is used for both omInUseList and omFreeList, so clear old before setting new
1347 m->FreeNext = Self->omFreeList;
1348 guarantee(m->is_free(), "invariant");
1349 Self->omFreeList = m;
1350 Self->omFreeCount++;
1351 }
1352
1353 // Return the monitors of a moribund thread's local free list to
1354 // the global free list. Typically a thread calls omFlush() when
1355 // it's dying. We could also consider having the VM thread steal
1356 // monitors from threads that have not run java code over a few
1357 // consecutive STW safepoints. Relatedly, we might decay
1358 // omFreeProvision at STW safepoints.
1359 //
1360 // Also return the monitors of a moribund thread's omInUseList to
1361 // a global gOmInUseList under the global list lock so these
1362 // will continue to be scanned.
1363 //
1364 // We currently call omFlush() from Threads::remove() _before the thread
1365 // has been excised from the thread list and is no longer a mutator.
1366 // This means that omFlush() cannot run concurrently with a safepoint and
1367 // interleave with the deflate_idle_monitors scavenge operator. In particular,
1368 // this ensures that the thread's monitors are scanned by a GC safepoint,
1369 // either via Thread::oops_do() (if safepoint happens before omFlush()) or via
1370 // ObjectSynchronizer::oops_do() (if it happens after omFlush() and the thread's
1371 // monitors have been transferred to the global in-use list).
1372 //
1373 // With AsyncDeflateIdleMonitors, deflate_global_idle_monitors_using_JT()
1374 // and deflate_per_thread_idle_monitors_using_JT() (in another thread) can
1375 // run at the same time as omFlush() so we have to be careful.
1376
1377 void ObjectSynchronizer::omFlush(Thread * Self) {
1378 ObjectMonitor * list = Self->omFreeList; // Null-terminated SLL
1379 ObjectMonitor * tail = NULL;
1380 int tally = 0;
1381 if (list != NULL) {
1382 ObjectMonitor * s;
1383 // The thread is going away, the per-thread free monitors
1384 // are freed via set_owner(NULL)
1385 // Link them to tail, which will be linked into the global free list
1386 // gFreeList below, under the gListLock
1387 for (s = list; s != NULL; s = s->FreeNext) {
1388 tally++;
1389 tail = s;
1390 guarantee(s->object() == NULL, "invariant");
1391 guarantee(!s->is_busy(), "invariant");
1392 s->set_owner(NULL); // redundant but good hygiene
1393 }
1394 guarantee(tail != NULL, "invariant");
1395 ADIM_guarantee(Self->omFreeCount == tally, "free-count off");
1396 Self->omFreeList = NULL;
1397 Self->omFreeCount = 0;
1398 }
1399
1400 ObjectMonitor * inUseList = Self->omInUseList;
1401 ObjectMonitor * inUseTail = NULL;
1402 int inUseTally = 0;
1403 if (inUseList != NULL) {
1404 ObjectMonitor *cur_om;
1405 // The thread is going away, however the omInUseList inflated
1406 // monitors may still be in-use by other threads.
1407 // Link them to inUseTail, which will be linked into the global in-use list
1408 // gOmInUseList below, under the gListLock
1409 for (cur_om = inUseList; cur_om != NULL; cur_om = cur_om->FreeNext) {
1410 inUseTail = cur_om;
1411 inUseTally++;
1412 ADIM_guarantee(cur_om->is_active(), "invariant");
1413 }
1414 guarantee(inUseTail != NULL, "invariant");
1415 ADIM_guarantee(Self->omInUseCount == inUseTally, "in-use count off");
1416 Self->omInUseList = NULL;
1417 Self->omInUseCount = 0;
1418 }
1419
1420 Thread::muxAcquire(&gListLock, "omFlush");
1421 if (tail != NULL) {
1422 tail->FreeNext = gFreeList;
1423 gFreeList = list;
1424 gMonitorFreeCount += tally;
1425 }
1426
1427 if (inUseTail != NULL) {
1428 inUseTail->FreeNext = gOmInUseList;
1429 gOmInUseList = inUseList;
1430 gOmInUseCount += inUseTally;
1431 }
1432
1433 Thread::muxRelease(&gListLock);
1434
1435 LogStreamHandle(Debug, monitorinflation) lsh_debug;
1443 }
1444 if (ls != NULL) {
1445 ls->print_cr("omFlush: jt=" INTPTR_FORMAT ", free_monitor_tally=%d"
1446 ", in_use_monitor_tally=%d" ", omFreeProvision=%d",
1447 p2i(Self), tally, inUseTally, Self->omFreeProvision);
1448 }
1449 }
1450
1451 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1452 const oop obj,
1453 ObjectSynchronizer::InflateCause cause) {
1454 assert(event != NULL, "invariant");
1455 assert(event->should_commit(), "invariant");
1456 event->set_monitorClass(obj->klass());
1457 event->set_address((uintptr_t)(void*)obj);
1458 event->set_cause((u1)cause);
1459 event->commit();
1460 }
1461
1462 // Fast path code shared by multiple functions
1463 void ObjectSynchronizer::inflate_helper(ObjectMonitorHandle * omh_p, oop obj) {
1464 while (true) {
1465 markOop mark = obj->mark();
1466 if (mark->has_monitor()) {
1467 if (!omh_p->save_om_ptr(obj, mark)) {
1468 // Lost a race with async deflation so try again.
1469 assert(AsyncDeflateIdleMonitors, "sanity check");
1470 continue;
1471 }
1472 ObjectMonitor * monitor = omh_p->om_ptr();
1473 assert(ObjectSynchronizer::verify_objmon_isinpool(monitor), "monitor is invalid");
1474 markOop dmw = monitor->header();
1475 assert(dmw->is_neutral(), "sanity check: header=" INTPTR_FORMAT, p2i(dmw));
1476 return;
1477 }
1478 inflate(omh_p, Thread::current(), obj, inflate_cause_vm_internal);
1479 return;
1480 }
1481 }
1482
1483 void ObjectSynchronizer::inflate(ObjectMonitorHandle * omh_p, Thread * Self,
1484 oop object, const InflateCause cause) {
1485 // Inflate mutates the heap ...
1486 // Relaxing assertion for bug 6320749.
1487 assert(Universe::verify_in_progress() ||
1488 !SafepointSynchronize::is_at_safepoint(), "invariant");
1489
1490 EventJavaMonitorInflate event;
1491
1492 for (;;) {
1493 const markOop mark = object->mark();
1494 assert(!mark->has_bias_pattern(), "invariant");
1495
1496 // The mark can be in one of the following states:
1497 // * Inflated - just return
1498 // * Stack-locked - coerce it to inflated
1499 // * INFLATING - busy wait for conversion to complete
1500 // * Neutral - aggressively inflate the object.
1501 // * BIASED - Illegal. We should never see this
1502
1503 // CASE: inflated
1504 if (mark->has_monitor()) {
1505 if (!omh_p->save_om_ptr(object, mark)) {
1506 // Lost a race with async deflation so try again.
1507 assert(AsyncDeflateIdleMonitors, "sanity check");
1508 continue;
1509 }
1510 ObjectMonitor * inf = omh_p->om_ptr();
1511 markOop dmw = inf->header();
1512 assert(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1513 assert(oopDesc::equals((oop) inf->object(), object), "invariant");
1514 assert(ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
1515 return;
1516 }
1517
1518 // CASE: inflation in progress - inflating over a stack-lock.
1519 // Some other thread is converting from stack-locked to inflated.
1520 // Only that thread can complete inflation -- other threads must wait.
1521 // The INFLATING value is transient.
1522 // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
1523 // We could always eliminate polling by parking the thread on some auxiliary list.
1524 if (mark == markOopDesc::INFLATING()) {
1525 ReadStableMark(object);
1526 continue;
1527 }
1528
1529 // CASE: stack-locked
1530 // Could be stack-locked either by this thread or by some other thread.
1531 //
1532 // Note that we allocate the objectmonitor speculatively, _before_ attempting
1533 // to install INFLATING into the mark word. We originally installed INFLATING,
1534 // allocated the objectmonitor, and then finally STed the address of the
1535 // objectmonitor into the mark. This was correct, but artificially lengthened
1536 // the interval in which INFLATED appeared in the mark, thus increasing
1537 // the odds of inflation contention.
1538 //
1539 // We now use per-thread private objectmonitor free lists.
1540 // These list are reprovisioned from the global free list outside the
1541 // critical INFLATING...ST interval. A thread can transfer
1542 // multiple objectmonitors en-mass from the global free list to its local free list.
1543 // This reduces coherency traffic and lock contention on the global free list.
1544 // Using such local free lists, it doesn't matter if the omAlloc() call appears
1545 // before or after the CAS(INFLATING) operation.
1546 // See the comments in omAlloc().
1547
1548 LogStreamHandle(Trace, monitorinflation) lsh;
1549
1550 if (mark->has_locker()) {
1551 ObjectMonitor * m;
1552 if (!AsyncDeflateIdleMonitors || cause == inflate_cause_vm_internal) {
1553 // If !AsyncDeflateIdleMonitors or if an internal inflation, then
1554 // we won't stop for a potential safepoint in omAlloc.
1555 m = omAlloc(Self, cause);
1556 } else {
1557 // If AsyncDeflateIdleMonitors and not an internal inflation, then
1558 // we may stop for a safepoint in omAlloc() so protect object.
1559 Handle h_obj(Self, object);
1560 m = omAlloc(Self, cause);
1561 object = h_obj(); // Refresh object.
1562 }
1563 // Optimistically prepare the objectmonitor - anticipate successful CAS
1564 // We do this before the CAS in order to minimize the length of time
1565 // in which INFLATING appears in the mark.
1566 m->Recycle();
1567 m->_Responsible = NULL;
1568 m->_recursions = 0;
1569 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // Consider: maintain by type/class
1570
1571 markOop cmp = object->cas_set_mark(markOopDesc::INFLATING(), mark);
1572 if (cmp != mark) {
1573 omRelease(Self, m, true);
1574 continue; // Interference -- just retry
1575 }
1576
1577 // We've successfully installed INFLATING (0) into the mark-word.
1578 // This is the only case where 0 will appear in a mark-word.
1579 // Only the singular thread that successfully swings the mark-word
1580 // to 0 can perform (or more precisely, complete) inflation.
1581 //
1582 // Why do we CAS a 0 into the mark-word instead of just CASing the
1590 // value from the basiclock on the owner's stack to the objectMonitor, all
1591 // the while preserving the hashCode stability invariants. If the owner
1592 // decides to release the lock while the value is 0, the unlock will fail
1593 // and control will eventually pass from slow_exit() to inflate. The owner
1594 // will then spin, waiting for the 0 value to disappear. Put another way,
1595 // the 0 causes the owner to stall if the owner happens to try to
1596 // drop the lock (restoring the header from the basiclock to the object)
1597 // while inflation is in-progress. This protocol avoids races that might
1598 // would otherwise permit hashCode values to change or "flicker" for an object.
1599 // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
1600 // 0 serves as a "BUSY" inflate-in-progress indicator.
1601
1602
1603 // fetch the displaced mark from the owner's stack.
1604 // The owner can't die or unwind past the lock while our INFLATING
1605 // object is in the mark. Furthermore the owner can't complete
1606 // an unlock on the object, either.
1607 markOop dmw = mark->displaced_mark_helper();
1608 // Catch if the object's header is not neutral (not locked and
1609 // not marked is what we care about here).
1610 ADIM_guarantee(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1611
1612 // Setup monitor fields to proper values -- prepare the monitor
1613 m->set_header(dmw);
1614
1615 // Optimization: if the mark->locker stack address is associated
1616 // with this thread we could simply set m->_owner = Self.
1617 // Note that a thread can inflate an object
1618 // that it has stack-locked -- as might happen in wait() -- directly
1619 // with CAS. That is, we can avoid the xchg-NULL .... ST idiom.
1620 m->set_owner(mark->locker());
1621 m->set_object(object);
1622 // TODO-FIXME: assert BasicLock->dhw != 0.
1623
1624 omh_p->set_om_ptr(m);
1625 assert(m->is_new(), "freshly allocated monitor must be new");
1626 m->set_allocation_state(ObjectMonitor::Old);
1627
1628 // Must preserve store ordering. The monitor state must
1629 // be stable at the time of publishing the monitor address.
1630 guarantee(object->mark() == markOopDesc::INFLATING(), "invariant");
1631 object->release_set_mark(markOopDesc::encode(m));
1632
1633 // Hopefully the performance counters are allocated on distinct cache lines
1634 // to avoid false sharing on MP systems ...
1635 OM_PERFDATA_OP(Inflations, inc());
1636 if (log_is_enabled(Trace, monitorinflation)) {
1637 ResourceMark rm(Self);
1638 lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark="
1639 INTPTR_FORMAT ", type='%s'", p2i(object),
1640 p2i(object->mark()), object->klass()->external_name());
1641 }
1642 if (event.should_commit()) {
1643 post_monitor_inflate_event(&event, object, cause);
1644 }
1645 ADIM_guarantee(!m->is_free(), "inflated monitor to be returned cannot be free");
1646 return;
1647 }
1648
1649 // CASE: neutral
1650 // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1651 // If we know we're inflating for entry it's better to inflate by swinging a
1652 // pre-locked objectMonitor pointer into the object header. A successful
1653 // CAS inflates the object *and* confers ownership to the inflating thread.
1654 // In the current implementation we use a 2-step mechanism where we CAS()
1655 // to inflate and then CAS() again to try to swing _owner from NULL to Self.
1656 // An inflateTry() method that we could call from fast_enter() and slow_enter()
1657 // would be useful.
1658
1659 // Catch if the object's header is not neutral (not locked and
1660 // not marked is what we care about here).
1661 ADIM_guarantee(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark));
1662 ObjectMonitor * m;
1663 if (!AsyncDeflateIdleMonitors || cause == inflate_cause_vm_internal) {
1664 // If !AsyncDeflateIdleMonitors or if an internal inflation, then
1665 // we won't stop for a potential safepoint in omAlloc.
1666 m = omAlloc(Self, cause);
1667 } else {
1668 // If AsyncDeflateIdleMonitors and not an internal inflation, then
1669 // we may stop for a safepoint in omAlloc() so protect object.
1670 Handle h_obj(Self, object);
1671 m = omAlloc(Self, cause);
1672 object = h_obj(); // Refresh object.
1673 }
1674 // prepare m for installation - set monitor to initial state
1675 m->Recycle();
1676 m->set_header(mark);
1677 m->set_owner(NULL);
1678 m->set_object(object);
1679 m->_recursions = 0;
1680 m->_Responsible = NULL;
1681 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // consider: keep metastats by type/class
1682
1683 omh_p->set_om_ptr(m);
1684 assert(m->is_new(), "freshly allocated monitor must be new");
1685 m->set_allocation_state(ObjectMonitor::Old);
1686
1687 if (object->cas_set_mark(markOopDesc::encode(m), mark) != mark) {
1688 m->set_header(NULL);
1689 m->set_object(NULL);
1690 m->Recycle();
1691 omh_p->set_om_ptr(NULL);
1692 // omRelease() will reset the allocation state
1693 omRelease(Self, m, true);
1694 m = NULL;
1695 continue;
1696 // interference - the markword changed - just retry.
1697 // The state-transitions are one-way, so there's no chance of
1698 // live-lock -- "Inflated" is an absorbing state.
1699 }
1700
1701 // Hopefully the performance counters are allocated on distinct
1702 // cache lines to avoid false sharing on MP systems ...
1703 OM_PERFDATA_OP(Inflations, inc());
1704 if (log_is_enabled(Trace, monitorinflation)) {
1705 ResourceMark rm(Self);
1706 lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark="
1707 INTPTR_FORMAT ", type='%s'", p2i(object),
1708 p2i(object->mark()), object->klass()->external_name());
1709 }
1710 if (event.should_commit()) {
1711 post_monitor_inflate_event(&event, object, cause);
1712 }
1713 ADIM_guarantee(!m->is_free(), "inflated monitor to be returned cannot be free");
1714 return;
1715 }
1716 }
1717
1718
1719 // We maintain a list of in-use monitors for each thread.
1720 //
1721 // deflate_thread_local_monitors() scans a single thread's in-use list, while
1722 // deflate_idle_monitors() scans only a global list of in-use monitors which
1723 // is populated only as a thread dies (see omFlush()).
1724 //
1725 // These operations are called at all safepoints, immediately after mutators
1726 // are stopped, but before any objects have moved. Collectively they traverse
1727 // the population of in-use monitors, deflating where possible. The scavenged
1728 // monitors are returned to the global monitor free list.
1729 //
1730 // Beware that we scavenge at *every* stop-the-world point. Having a large
1731 // number of monitors in-use could negatively impact performance. We also want
1732 // to minimize the total # of monitors in circulation, as they incur a small
1733 // footprint penalty.
1734 //
1735 // Perversely, the heap size -- and thus the STW safepoint rate --
1736 // typically drives the scavenge rate. Large heaps can mean infrequent GC,
1737 // which in turn can mean large(r) numbers of ObjectMonitors in circulation.
1738 // This is an unfortunate aspect of this design.
1739
1740 void ObjectSynchronizer::do_safepoint_work(DeflateMonitorCounters* _counters) {
1741 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1742
1743 // The per-thread in-use lists are handled in
1744 // ParallelSPCleanupThreadClosure::do_thread().
1745
1746 if (!AsyncDeflateIdleMonitors || is_special_deflation_requested()) {
1747 // Use the older mechanism for the global in-use list or if a
1748 // special deflation has been requested before the safepoint.
1749 ObjectSynchronizer::deflate_idle_monitors(_counters);
1750 return;
1751 }
1752
1753 log_debug(monitorinflation)("requesting async deflation of idle monitors.");
1754 // Request deflation of idle monitors by the ServiceThread:
1755 set_is_async_deflation_requested(true);
1756 MonitorLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
1757 ml.notify_all();
1758 }
1759
1760 // Deflate a single monitor if not in-use
1761 // Return true if deflated, false if in-use
1762 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
1763 ObjectMonitor** freeHeadp,
1764 ObjectMonitor** freeTailp) {
1765 bool deflated;
1766 // Normal case ... The monitor is associated with obj.
1767 const markOop mark = obj->mark();
1768 guarantee(mark == markOopDesc::encode(mid), "should match: mark="
1769 INTPTR_FORMAT ", encoded mid=" INTPTR_FORMAT, p2i(mark),
1770 p2i(markOopDesc::encode(mid)));
1771 // Make sure that mark->monitor() and markOopDesc::encode() agree:
1772 guarantee(mark->monitor() == mid, "should match: monitor()=" INTPTR_FORMAT
1773 ", mid=" INTPTR_FORMAT, p2i(mark->monitor()), p2i(mid));
1774 const markOop dmw = mid->header();
1775 guarantee(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1776
1777 if (mid->is_busy()) {
1778 deflated = false;
1779 } else {
1780 // Deflate the monitor if it is no longer being used
1781 // It's idle - scavenge and return to the global free list
1782 // plain old deflation ...
1783 if (log_is_enabled(Trace, monitorinflation)) {
1784 ResourceMark rm;
1785 log_trace(monitorinflation)("deflate_monitor: "
1786 "object=" INTPTR_FORMAT ", mark="
1787 INTPTR_FORMAT ", type='%s'", p2i(obj),
1788 p2i(mark), obj->klass()->external_name());
1789 }
1790
1791 // Restore the header back to obj
1792 obj->release_set_mark(dmw);
1793 mid->clear();
1794
1795 assert(mid->object() == NULL, "invariant: object=" INTPTR_FORMAT,
1796 p2i(mid->object()));
1797 assert(mid->is_free(), "invariant");
1798
1799 // Move the object to the working free list defined by freeHeadp, freeTailp
1800 if (*freeHeadp == NULL) *freeHeadp = mid;
1801 if (*freeTailp != NULL) {
1802 ObjectMonitor * prevtail = *freeTailp;
1803 assert(prevtail->FreeNext == NULL, "cleaned up deflated?");
1804 prevtail->FreeNext = mid;
1805 }
1806 *freeTailp = mid;
1807 deflated = true;
1808 }
1809 return deflated;
1810 }
1811
1812 // Deflate the specified ObjectMonitor if not in-use using a JavaThread.
1813 // Returns true if it was deflated and false otherwise.
1814 //
1815 // The async deflation protocol sets owner to DEFLATER_MARKER and
1816 // makes ref_count negative as signals to contending threads that
1817 // an async deflation is in progress. There are a number of checks
1818 // as part of the protocol to make sure that the calling thread has
1819 // not lost the race to a contending thread or to a thread that just
1820 // wants to use the ObjectMonitor*.
1821 //
1822 // The ObjectMonitor has been successfully async deflated when:
1823 // (owner == DEFLATER_MARKER && ref_count < 0)
1824 // Contending threads or ObjectMonitor* using threads that see those
1825 // values know to retry their operation.
1826 //
1827 bool ObjectSynchronizer::deflate_monitor_using_JT(ObjectMonitor* mid,
1828 ObjectMonitor** freeHeadp,
1829 ObjectMonitor** freeTailp) {
1830 assert(AsyncDeflateIdleMonitors, "sanity check");
1831 assert(Thread::current()->is_Java_thread(), "precondition");
1832 // A newly allocated ObjectMonitor should not be seen here so we
1833 // avoid an endless inflate/deflate cycle.
1834 assert(mid->is_old(), "must be old: allocation_state=%d",
1835 (int) mid->allocation_state());
1836
1837 if (mid->is_busy() || mid->ref_count() != 0) {
1838 // Easy checks are first - the ObjectMonitor is busy or ObjectMonitor*
1839 // is in use so no deflation.
1840 return false;
1841 }
1842
1843 if (Atomic::replace_if_null(DEFLATER_MARKER, &(mid->_owner))) {
1844 // ObjectMonitor is not owned by another thread. Our setting
1845 // owner to DEFLATER_MARKER forces any contending thread through
1846 // the slow path. This is just the first part of the async
1847 // deflation dance.
1848
1849 if (mid->_contentions != 0 || mid->_waiters != 0) {
1850 // Another thread has raced to enter the ObjectMonitor after
1851 // mid->is_busy() above or has already entered and waited on
1852 // it which makes it busy so no deflation. Restore owner to
1853 // NULL if it is still DEFLATER_MARKER.
1854 Atomic::cmpxchg((void*)NULL, &mid->_owner, DEFLATER_MARKER);
1855 return false;
1856 }
1857
1858 if (Atomic::cmpxchg(-max_jint, &mid->_ref_count, (jint)0) == 0) {
1859 // Make ref_count negative to force any contending threads or
1860 // ObjectMonitor* using threads to retry. This is the second
1861 // part of the async deflation dance.
1862
1863 if (mid->_owner == DEFLATER_MARKER) {
1864 // If owner is still DEFLATER_MARKER, then we have successfully
1865 // signaled any contending threads to retry. If it is not, then we
1866 // have lost the race to an entering thread and the ObjectMonitor
1867 // is now busy. This is the third and final part of the async
1868 // deflation dance.
1869 // Note: This owner check solves the ABA problem with ref_count
1870 // where another thread acquired the ObjectMonitor, finished
1871 // using it and restored the ref_count to zero.
1872
1873 // Sanity checks for the races:
1874 guarantee(mid->_contentions == 0, "must be 0: contentions=%d",
1875 mid->_contentions);
1876 guarantee(mid->_waiters == 0, "must be 0: waiters=%d", mid->_waiters);
1877 guarantee(mid->_cxq == NULL, "must be no contending threads: cxq="
1878 INTPTR_FORMAT, p2i(mid->_cxq));
1879 guarantee(mid->_EntryList == NULL,
1880 "must be no entering threads: EntryList=" INTPTR_FORMAT,
1881 p2i(mid->_EntryList));
1882
1883 const oop obj = (oop) mid->object();
1884 if (log_is_enabled(Trace, monitorinflation)) {
1885 ResourceMark rm;
1886 log_trace(monitorinflation)("deflate_monitor_using_JT: "
1887 "object=" INTPTR_FORMAT ", mark="
1888 INTPTR_FORMAT ", type='%s'",
1889 p2i(obj), p2i(obj->mark()),
1890 obj->klass()->external_name());
1891 }
1892
1893 // Install the old mark word if nobody else has already done it.
1894 mid->install_displaced_markword_in_object(obj);
1895 mid->clear_using_JT();
1896
1897 assert(mid->object() == NULL, "must be NULL: object=" INTPTR_FORMAT,
1898 p2i(mid->object()));
1899 assert(mid->is_free(), "must be free: allocation_state=%d",
1900 (int) mid->allocation_state());
1901
1902 // Move the deflated ObjectMonitor to the working free list
1903 // defined by freeHeadp and freeTailp.
1904 if (*freeHeadp == NULL) {
1905 // First one on the list.
1906 *freeHeadp = mid;
1907 }
1908 if (*freeTailp != NULL) {
1909 // We append to the list so the caller can use mid->FreeNext
1910 // to fix the linkages in its context.
1911 ObjectMonitor * prevtail = *freeTailp;
1912 // Should have been cleaned up by the caller:
1913 assert(prevtail->FreeNext == NULL, "must be NULL: FreeNext="
1914 INTPTR_FORMAT, p2i(prevtail->FreeNext));
1915 prevtail->FreeNext = mid;
1916 }
1917 *freeTailp = mid;
1918
1919 // At this point, mid->FreeNext still refers to its current
1920 // value and another ObjectMonitor's FreeNext field still
1921 // refers to this ObjectMonitor. Those linkages have to be
1922 // cleaned up by the caller who has the complete context.
1923
1924 // We leave owner == DEFLATER_MARKER and ref_count < 0
1925 // to force any racing threads to retry.
1926 return true; // Success, ObjectMonitor has been deflated.
1927 }
1928
1929 // The owner was changed from DEFLATER_MARKER so we lost the
1930 // race since the ObjectMonitor is now busy.
1931
1932 // Add back max_jint to restore the ref_count field to its
1933 // proper value (which may not be what we saw above):
1934 Atomic::add(max_jint, &mid->_ref_count);
1935
1936 assert(mid->ref_count() >= 0, "must not be negative: ref_count=%d",
1937 mid->ref_count());
1938 return false;
1939 }
1940
1941 // The ref_count was no longer 0 so we lost the race since the
1942 // ObjectMonitor is now busy or the ObjectMonitor* is now is use.
1943 // Restore owner to NULL if it is still DEFLATER_MARKER:
1944 Atomic::cmpxchg((void*)NULL, &mid->_owner, DEFLATER_MARKER);
1945 }
1946
1947 // The owner field is no longer NULL so we lost the race since the
1948 // ObjectMonitor is now busy.
1949 return false;
1950 }
1951
1952 // Walk a given monitor list, and deflate idle monitors
1953 // The given list could be a per-thread list or a global list
1954 // Caller acquires gListLock as needed.
1955 //
1956 // In the case of parallel processing of thread local monitor lists,
1957 // work is done by Threads::parallel_threads_do() which ensures that
1958 // each Java thread is processed by exactly one worker thread, and
1959 // thus avoid conflicts that would arise when worker threads would
1960 // process the same monitor lists concurrently.
1961 //
1962 // See also ParallelSPCleanupTask and
1963 // SafepointSynchronize::do_cleanup_tasks() in safepoint.cpp and
1964 // Threads::parallel_java_threads_do() in thread.cpp.
1965 int ObjectSynchronizer::deflate_monitor_list(ObjectMonitor** listHeadp,
1966 ObjectMonitor** freeHeadp,
1967 ObjectMonitor** freeTailp) {
1968 ObjectMonitor* mid;
1969 ObjectMonitor* next;
1970 ObjectMonitor* cur_mid_in_use = NULL;
1971 int deflated_count = 0;
1975 if (obj != NULL && deflate_monitor(mid, obj, freeHeadp, freeTailp)) {
1976 // if deflate_monitor succeeded,
1977 // extract from per-thread in-use list
1978 if (mid == *listHeadp) {
1979 *listHeadp = mid->FreeNext;
1980 } else if (cur_mid_in_use != NULL) {
1981 cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1982 }
1983 next = mid->FreeNext;
1984 mid->FreeNext = NULL; // This mid is current tail in the freeHeadp list
1985 mid = next;
1986 deflated_count++;
1987 } else {
1988 cur_mid_in_use = mid;
1989 mid = mid->FreeNext;
1990 }
1991 }
1992 return deflated_count;
1993 }
1994
1995 // Walk a given ObjectMonitor list and deflate idle ObjectMonitors using
1996 // a JavaThread. Returns the number of deflated ObjectMonitors. The given
1997 // list could be a per-thread in-use list or the global in-use list.
1998 // Caller acquires gListLock as appropriate. If a safepoint has started,
1999 // then we save state via savedMidInUsep and return to the caller to
2000 // honor the safepoint.
2001 //
2002 int ObjectSynchronizer::deflate_monitor_list_using_JT(ObjectMonitor** listHeadp,
2003 ObjectMonitor** freeHeadp,
2004 ObjectMonitor** freeTailp,
2005 ObjectMonitor** savedMidInUsep) {
2006 assert(AsyncDeflateIdleMonitors, "sanity check");
2007 assert(Thread::current()->is_Java_thread(), "precondition");
2008
2009 ObjectMonitor* mid;
2010 ObjectMonitor* next;
2011 ObjectMonitor* cur_mid_in_use = NULL;
2012 int deflated_count = 0;
2013
2014 if (*savedMidInUsep == NULL) {
2015 // No saved state so start at the beginning.
2016 mid = *listHeadp;
2017 } else {
2018 // We're restarting after a safepoint so restore the necessary state
2019 // before we resume.
2020 cur_mid_in_use = *savedMidInUsep;
2021 mid = cur_mid_in_use->FreeNext;
2022 }
2023 while (mid != NULL) {
2024 // Only try to deflate if there is an associated Java object and if
2025 // mid is old (is not newly allocated and is not newly freed).
2026 if (mid->object() != NULL && mid->is_old() &&
2027 deflate_monitor_using_JT(mid, freeHeadp, freeTailp)) {
2028 // Deflation succeeded so update the in-use list.
2029 if (mid == *listHeadp) {
2030 *listHeadp = mid->FreeNext;
2031 } else if (cur_mid_in_use != NULL) {
2032 // Maintain the current in-use list.
2033 cur_mid_in_use->FreeNext = mid->FreeNext;
2034 }
2035 next = mid->FreeNext;
2036 mid->FreeNext = NULL;
2037 // At this point mid is disconnected from the in-use list
2038 // and is the current tail in the freeHeadp list.
2039 mid = next;
2040 deflated_count++;
2041 } else {
2042 // mid is considered in-use if it does not have an associated
2043 // Java object or mid is not old or deflation did not succeed.
2044 // A mid->is_new() node can be seen here when it is freshly
2045 // returned by omAlloc() (and skips the deflation code path).
2046 // A mid->is_old() node can be seen here when deflation failed.
2047 // A mid->is_free() node can be seen here when a fresh node from
2048 // omAlloc() is released by omRelease() due to losing the race
2049 // in inflate().
2050
2051 cur_mid_in_use = mid;
2052 mid = mid->FreeNext;
2053
2054 if (SafepointSynchronize::is_synchronizing() &&
2055 cur_mid_in_use != *listHeadp && cur_mid_in_use->is_old()) {
2056 // If a safepoint has started and cur_mid_in_use is not the list
2057 // head and is old, then it is safe to use as saved state. Return
2058 // to the caller so gListLock can be dropped as appropriate
2059 // before blocking.
2060 *savedMidInUsep = cur_mid_in_use;
2061 return deflated_count;
2062 }
2063 }
2064 }
2065 // We finished the list without a safepoint starting so there's
2066 // no need to save state.
2067 *savedMidInUsep = NULL;
2068 return deflated_count;
2069 }
2070
2071 void ObjectSynchronizer::prepare_deflate_idle_monitors(DeflateMonitorCounters* counters) {
2072 counters->nInuse = 0; // currently associated with objects
2073 counters->nInCirculation = 0; // extant
2074 counters->nScavenged = 0; // reclaimed (global and per-thread)
2075 counters->perThreadScavenged = 0; // per-thread scavenge total
2076 counters->perThreadTimes = 0.0; // per-thread scavenge times
2077 }
2078
2079 void ObjectSynchronizer::deflate_idle_monitors(DeflateMonitorCounters* counters) {
2080 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2081
2082 if (AsyncDeflateIdleMonitors) {
2083 // Nothing to do when global idle ObjectMonitors are deflated using
2084 // a JavaThread unless a special deflation has been requested.
2085 if (!is_special_deflation_requested()) {
2086 return;
2087 }
2088 }
2089
2090 bool deflated = false;
2091
2092 ObjectMonitor * freeHeadp = NULL; // Local SLL of scavenged monitors
2093 ObjectMonitor * freeTailp = NULL;
2094 elapsedTimer timer;
2095
2096 if (log_is_enabled(Info, monitorinflation)) {
2097 timer.start();
2098 }
2099
2100 // Prevent omFlush from changing mids in Thread dtor's during deflation
2101 // And in case the vm thread is acquiring a lock during a safepoint
2102 // See e.g. 6320749
2103 Thread::muxAcquire(&gListLock, "deflate_idle_monitors");
2104
2105 // Note: the thread-local monitors lists get deflated in
2106 // a separate pass. See deflate_thread_local_monitors().
2107
2108 // For moribund threads, scan gOmInUseList
2109 int deflated_count = 0;
2122 // constant-time list splice - prepend scavenged segment to gFreeList
2123 freeTailp->FreeNext = gFreeList;
2124 gFreeList = freeHeadp;
2125 }
2126 Thread::muxRelease(&gListLock);
2127 timer.stop();
2128
2129 LogStreamHandle(Debug, monitorinflation) lsh_debug;
2130 LogStreamHandle(Info, monitorinflation) lsh_info;
2131 LogStream * ls = NULL;
2132 if (log_is_enabled(Debug, monitorinflation)) {
2133 ls = &lsh_debug;
2134 } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
2135 ls = &lsh_info;
2136 }
2137 if (ls != NULL) {
2138 ls->print_cr("deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count);
2139 }
2140 }
2141
2142 // Deflate global idle ObjectMonitors using a JavaThread.
2143 //
2144 void ObjectSynchronizer::deflate_global_idle_monitors_using_JT() {
2145 assert(AsyncDeflateIdleMonitors, "sanity check");
2146 assert(Thread::current()->is_Java_thread(), "precondition");
2147 JavaThread * self = JavaThread::current();
2148
2149 deflate_common_idle_monitors_using_JT(true /* is_global */, self);
2150 }
2151
2152 // Deflate per-thread idle ObjectMonitors using a JavaThread.
2153 //
2154 void ObjectSynchronizer::deflate_per_thread_idle_monitors_using_JT() {
2155 assert(AsyncDeflateIdleMonitors, "sanity check");
2156 assert(Thread::current()->is_Java_thread(), "precondition");
2157 JavaThread * self = JavaThread::current();
2158
2159 self->omShouldDeflateIdleMonitors = false;
2160
2161 deflate_common_idle_monitors_using_JT(false /* !is_global */, self);
2162 }
2163
2164 // Deflate global or per-thread idle ObjectMonitors using a JavaThread.
2165 //
2166 void ObjectSynchronizer::deflate_common_idle_monitors_using_JT(bool is_global, JavaThread * self) {
2167 int deflated_count = 0;
2168 ObjectMonitor * freeHeadp = NULL; // Local SLL of scavenged ObjectMonitors
2169 ObjectMonitor * freeTailp = NULL;
2170 ObjectMonitor * savedMidInUsep = NULL;
2171 elapsedTimer timer;
2172
2173 if (log_is_enabled(Info, monitorinflation)) {
2174 timer.start();
2175 }
2176
2177 if (is_global) {
2178 Thread::muxAcquire(&gListLock, "deflate_global_idle_monitors_using_JT(1)");
2179 OM_PERFDATA_OP(MonExtant, set_value(gOmInUseCount));
2180 } else {
2181 OM_PERFDATA_OP(MonExtant, inc(self->omInUseCount));
2182 }
2183
2184 do {
2185 int local_deflated_count;
2186 if (is_global) {
2187 local_deflated_count = deflate_monitor_list_using_JT((ObjectMonitor **)&gOmInUseList, &freeHeadp, &freeTailp, &savedMidInUsep);
2188 gOmInUseCount -= local_deflated_count;
2189 } else {
2190 local_deflated_count = deflate_monitor_list_using_JT(self->omInUseList_addr(), &freeHeadp, &freeTailp, &savedMidInUsep);
2191 self->omInUseCount -= local_deflated_count;
2192 }
2193 deflated_count += local_deflated_count;
2194
2195 if (freeHeadp != NULL) {
2196 // Move the scavenged ObjectMonitors to the global free list.
2197 guarantee(freeTailp != NULL && local_deflated_count > 0, "freeTailp=" INTPTR_FORMAT ", local_deflated_count=%d", p2i(freeTailp), local_deflated_count);
2198 assert(freeTailp->FreeNext == NULL, "invariant");
2199
2200 if (!is_global) {
2201 Thread::muxAcquire(&gListLock, "deflate_per_thread_idle_monitors_using_JT(2)");
2202 }
2203 // Constant-time list splice - prepend scavenged segment to gFreeList.
2204 freeTailp->FreeNext = gFreeList;
2205 gFreeList = freeHeadp;
2206
2207 gMonitorFreeCount += local_deflated_count;
2208 OM_PERFDATA_OP(Deflations, inc(local_deflated_count));
2209 if (!is_global) {
2210 Thread::muxRelease(&gListLock);
2211 }
2212 }
2213
2214 if (savedMidInUsep != NULL) {
2215 // deflate_monitor_list_using_JT() detected a safepoint starting.
2216 if (is_global) {
2217 Thread::muxRelease(&gListLock);
2218 }
2219 timer.stop();
2220 {
2221 if (is_global) {
2222 log_debug(monitorinflation)("pausing deflation of global idle monitors for a safepoint.");
2223 } else {
2224 log_debug(monitorinflation)("jt=" INTPTR_FORMAT ": pausing deflation of per-thread idle monitors for a safepoint.", p2i(self));
2225 }
2226 assert(SafepointSynchronize::is_synchronizing(), "sanity check");
2227 ThreadBlockInVM blocker(self);
2228 }
2229 // Prepare for another loop after the safepoint.
2230 freeHeadp = NULL;
2231 freeTailp = NULL;
2232 if (log_is_enabled(Info, monitorinflation)) {
2233 timer.start();
2234 }
2235 if (is_global) {
2236 Thread::muxAcquire(&gListLock, "deflate_global_idle_monitors_using_JT(3)");
2237 }
2238 }
2239 } while (savedMidInUsep != NULL);
2240 if (is_global) {
2241 Thread::muxRelease(&gListLock);
2242 }
2243 timer.stop();
2244
2245 LogStreamHandle(Debug, monitorinflation) lsh_debug;
2246 LogStreamHandle(Info, monitorinflation) lsh_info;
2247 LogStream * ls = NULL;
2248 if (log_is_enabled(Debug, monitorinflation)) {
2249 ls = &lsh_debug;
2250 } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
2251 ls = &lsh_info;
2252 }
2253 if (ls != NULL) {
2254 if (is_global) {
2255 ls->print_cr("async-deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count);
2256 } else {
2257 ls->print_cr("jt=" INTPTR_FORMAT ": async-deflating per-thread idle monitors, %3.7f secs, %d monitors", p2i(self), timer.seconds(), deflated_count);
2258 }
2259 }
2260 }
2261
2262 void ObjectSynchronizer::finish_deflate_idle_monitors(DeflateMonitorCounters* counters) {
2263 // Report the cumulative time for deflating each thread's idle
2264 // monitors. Note: if the work is split among more than one
2265 // worker thread, then the reported time will likely be more
2266 // than a beginning to end measurement of the phase.
2267 // Note: AsyncDeflateIdleMonitors only deflates per-thread idle
2268 // monitors at a safepoint when a special deflation has been requested.
2269 log_info(safepoint, cleanup)("deflating per-thread idle monitors, %3.7f secs, monitors=%d", counters->perThreadTimes, counters->perThreadScavenged);
2270
2271 bool needs_special_deflation = is_special_deflation_requested();
2272 if (!AsyncDeflateIdleMonitors || needs_special_deflation) {
2273 // AsyncDeflateIdleMonitors does not use these counters unless
2274 // there is a special deflation request.
2275
2276 gMonitorFreeCount += counters->nScavenged;
2277
2278 OM_PERFDATA_OP(Deflations, inc(counters->nScavenged));
2279 OM_PERFDATA_OP(MonExtant, set_value(counters->nInCirculation));
2280 }
2281
2282 if (log_is_enabled(Debug, monitorinflation)) {
2283 // exit_globals()'s call to audit_and_print_stats() is done
2284 // at the Info level.
2285 ObjectSynchronizer::audit_and_print_stats(false /* on_exit */);
2286 } else if (log_is_enabled(Info, monitorinflation)) {
2287 Thread::muxAcquire(&gListLock, "finish_deflate_idle_monitors");
2288 log_info(monitorinflation)("gMonitorPopulation=%d, gOmInUseCount=%d, "
2289 "gMonitorFreeCount=%d", gMonitorPopulation,
2290 gOmInUseCount, gMonitorFreeCount);
2291 Thread::muxRelease(&gListLock);
2292 }
2293
2294 ForceMonitorScavenge = 0; // Reset
2295 GVars.stwRandom = os::random();
2296 GVars.stwCycle++;
2297 if (needs_special_deflation) {
2298 set_is_special_deflation_requested(false); // special deflation is done
2299 }
2300 }
2301
2302 void ObjectSynchronizer::deflate_thread_local_monitors(Thread* thread, DeflateMonitorCounters* counters) {
2303 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2304
2305 if (AsyncDeflateIdleMonitors) {
2306 if (!is_special_deflation_requested()) {
2307 // Mark the JavaThread for idle monitor deflation if a special
2308 // deflation has NOT been requested.
2309 if (thread->omInUseCount > 0) {
2310 // This JavaThread is using monitors so mark it.
2311 thread->omShouldDeflateIdleMonitors = true;
2312 }
2313 return;
2314 }
2315 }
2316
2317 ObjectMonitor * freeHeadp = NULL; // Local SLL of scavenged monitors
2318 ObjectMonitor * freeTailp = NULL;
2319 elapsedTimer timer;
2320
2321 if (log_is_enabled(Info, safepoint, cleanup) ||
2322 log_is_enabled(Info, monitorinflation)) {
2323 timer.start();
2324 }
2325
2326 int deflated_count = deflate_monitor_list(thread->omInUseList_addr(), &freeHeadp, &freeTailp);
2327
2328 Thread::muxAcquire(&gListLock, "deflate_thread_local_monitors");
2329
2330 // Adjust counters
2331 counters->nInCirculation += thread->omInUseCount;
2332 thread->omInUseCount -= deflated_count;
2333 counters->nScavenged += deflated_count;
2334 counters->nInuse += thread->omInUseCount;
2335 counters->perThreadScavenged += deflated_count;
2336
2505 } else {
2506 log_error(monitorinflation)("found monitor list errors: error_cnt=%d", error_cnt);
2507 }
2508
2509 if ((on_exit && log_is_enabled(Info, monitorinflation)) ||
2510 (!on_exit && log_is_enabled(Trace, monitorinflation))) {
2511 // When exiting this log output is at the Info level. When called
2512 // at a safepoint, this log output is at the Trace level since
2513 // there can be a lot of it.
2514 log_in_use_monitor_details(ls, on_exit);
2515 }
2516
2517 ls->flush();
2518
2519 guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
2520 }
2521
2522 // Check a free monitor entry; log any errors.
2523 void ObjectSynchronizer::chk_free_entry(JavaThread * jt, ObjectMonitor * n,
2524 outputStream * out, int *error_cnt_p) {
2525 if ((!AsyncDeflateIdleMonitors && n->is_busy()) ||
2526 (AsyncDeflateIdleMonitors && n->is_busy_async())) {
2527 if (jt != NULL) {
2528 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2529 ": free per-thread monitor must not be busy.", p2i(jt),
2530 p2i(n));
2531 } else {
2532 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2533 "must not be busy.", p2i(n));
2534 }
2535 *error_cnt_p = *error_cnt_p + 1;
2536 }
2537 if (n->header() != NULL) {
2538 if (jt != NULL) {
2539 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2540 ": free per-thread monitor must have NULL _header "
2541 "field: _header=" INTPTR_FORMAT, p2i(jt), p2i(n),
2542 p2i(n->header()));
2543 *error_cnt_p = *error_cnt_p + 1;
2544 } else if (!AsyncDeflateIdleMonitors) {
2545 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2546 "must have NULL _header field: _header=" INTPTR_FORMAT,
2547 p2i(n), p2i(n->header()));
2548 *error_cnt_p = *error_cnt_p + 1;
2549 }
2550 }
2551 if (n->object() != NULL) {
2552 if (jt != NULL) {
2553 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2554 ": free per-thread monitor must have NULL _object "
2555 "field: _object=" INTPTR_FORMAT, p2i(jt), p2i(n),
2556 p2i(n->object()));
2557 } else {
2558 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
2559 "must have NULL _object field: _object=" INTPTR_FORMAT,
2560 p2i(n), p2i(n->object()));
2561 }
2562 *error_cnt_p = *error_cnt_p + 1;
2563 }
2564 }
2565
2566 // Check the global free list and count; log the results of the checks.
2567 void ObjectSynchronizer::chk_global_free_list_and_count(outputStream * out,
2568 int *error_cnt_p) {
2569 int chkMonitorFreeCount = 0;
2570 for (ObjectMonitor * n = gFreeList; n != NULL; n = n->FreeNext) {
2696 out->print_cr("ERROR: jt=" INTPTR_FORMAT ": omInUseCount=%d is not "
2697 "equal to chkOmInUseCount=%d", p2i(jt), jt->omInUseCount,
2698 chkOmInUseCount);
2699 *error_cnt_p = *error_cnt_p + 1;
2700 }
2701 }
2702
2703 // Log details about ObjectMonitors on the in-use lists. The 'BHL'
2704 // flags indicate why the entry is in-use, 'object' and 'object type'
2705 // indicate the associated object and its type.
2706 void ObjectSynchronizer::log_in_use_monitor_details(outputStream * out,
2707 bool on_exit) {
2708 if (!on_exit) {
2709 // Not at VM exit so grab the global list lock.
2710 Thread::muxAcquire(&gListLock, "log_in_use_monitor_details");
2711 }
2712
2713 if (gOmInUseCount > 0) {
2714 out->print_cr("In-use global monitor info:");
2715 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2716 out->print_cr("%18s %s %7s %18s %18s",
2717 "monitor", "BHL", "ref_cnt", "object", "object type");
2718 out->print_cr("================== === ======= ================== ==================");
2719 for (ObjectMonitor * n = gOmInUseList; n != NULL; n = n->FreeNext) {
2720 const oop obj = (oop) n->object();
2721 const markOop mark = n->header();
2722 ResourceMark rm;
2723 out->print_cr(INTPTR_FORMAT " %d%d%d %7d " INTPTR_FORMAT " %s",
2724 p2i(n), n->is_busy() != 0, mark->hash() != 0,
2725 n->owner() != NULL, (int)n->ref_count(), p2i(obj),
2726 obj->klass()->external_name());
2727 }
2728 }
2729
2730 if (!on_exit) {
2731 Thread::muxRelease(&gListLock);
2732 }
2733
2734 out->print_cr("In-use per-thread monitor info:");
2735 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2736 out->print_cr("%18s %18s %s %7s %18s %18s",
2737 "jt", "monitor", "BHL", "ref_cnt", "object", "object type");
2738 out->print_cr("================== ================== === ======= ================== ==================");
2739 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2740 for (ObjectMonitor * n = jt->omInUseList; n != NULL; n = n->FreeNext) {
2741 const oop obj = (oop) n->object();
2742 const markOop mark = n->header();
2743 ResourceMark rm;
2744 out->print_cr(INTPTR_FORMAT " " INTPTR_FORMAT " %d%d%d %7d "
2745 INTPTR_FORMAT " %s", p2i(jt), p2i(n), n->is_busy() != 0,
2746 mark->hash() != 0, n->owner() != NULL, (int)n->ref_count(),
2747 p2i(obj), obj->klass()->external_name());
2748 }
2749 }
2750
2751 out->flush();
2752 }
2753
2754 // Log counts for the global and per-thread monitor lists and return
2755 // the population count.
2756 int ObjectSynchronizer::log_monitor_list_counts(outputStream * out) {
2757 int popCount = 0;
2758 out->print_cr("%18s %10s %10s %10s",
2759 "Global Lists:", "InUse", "Free", "Total");
2760 out->print_cr("================== ========== ========== ==========");
2761 out->print_cr("%18s %10d %10d %10d", "",
2762 gOmInUseCount, gMonitorFreeCount, gMonitorPopulation);
2763 popCount += gOmInUseCount + gMonitorFreeCount;
2764
2765 out->print_cr("%18s %10s %10s %10s",
2766 "Per-Thread Lists:", "InUse", "Free", "Provision");
2767 out->print_cr("================== ========== ========== ==========");
|