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