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