-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathsynchronizer.cpp
2009 lines (1775 loc) · 80.4 KB
/
synchronizer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/vmSymbols.hpp"
#include "gc/shared/collectedHeap.hpp"
#include "jfr/jfrEvents.hpp"
#include "logging/log.hpp"
#include "logging/logStream.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/padded.hpp"
#include "memory/resourceArea.hpp"
#include "memory/universe.hpp"
#include "oops/markWord.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/atomic.hpp"
#include "runtime/frame.inline.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/handshake.hpp"
#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/javaThread.hpp"
#include "runtime/lockStack.inline.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/objectMonitor.hpp"
#include "runtime/objectMonitor.inline.hpp"
#include "runtime/os.inline.hpp"
#include "runtime/osThread.hpp"
#include "runtime/perfData.hpp"
#include "runtime/safepointMechanism.inline.hpp"
#include "runtime/safepointVerifiers.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/synchronizer.hpp"
#include "runtime/threads.hpp"
#include "runtime/timer.hpp"
#include "runtime/trimNativeHeap.hpp"
#include "runtime/vframe.hpp"
#include "runtime/vmThread.hpp"
#include "utilities/align.hpp"
#include "utilities/dtrace.hpp"
#include "utilities/events.hpp"
#include "utilities/linkedlist.hpp"
#include "utilities/preserveException.hpp"
class ObjectMonitorDeflationLogging;
void MonitorList::add(ObjectMonitor* m) {
ObjectMonitor* head;
do {
head = Atomic::load(&_head);
m->set_next_om(head);
} while (Atomic::cmpxchg(&_head, head, m) != head);
size_t count = Atomic::add(&_count, 1u);
if (count > max()) {
Atomic::inc(&_max);
}
}
size_t MonitorList::count() const {
return Atomic::load(&_count);
}
size_t MonitorList::max() const {
return Atomic::load(&_max);
}
class ObjectMonitorDeflationSafepointer : public StackObj {
JavaThread* const _current;
ObjectMonitorDeflationLogging* const _log;
public:
ObjectMonitorDeflationSafepointer(JavaThread* current, ObjectMonitorDeflationLogging* log)
: _current(current), _log(log) {}
void block_for_safepoint(const char* op_name, const char* count_name, size_t counter);
};
// Walk the in-use list and unlink deflated ObjectMonitors.
// Returns the number of unlinked ObjectMonitors.
size_t MonitorList::unlink_deflated(size_t deflated_count,
GrowableArray<ObjectMonitor*>* unlinked_list,
ObjectMonitorDeflationSafepointer* safepointer) {
size_t unlinked_count = 0;
ObjectMonitor* prev = nullptr;
ObjectMonitor* m = Atomic::load_acquire(&_head);
while (m != nullptr) {
if (m->is_being_async_deflated()) {
// Find next live ObjectMonitor. Batch up the unlinkable monitors, so we can
// modify the list once per batch. The batch starts at "m".
size_t unlinked_batch = 0;
ObjectMonitor* next = m;
// Look for at most MonitorUnlinkBatch monitors, or the number of
// deflated and not unlinked monitors, whatever comes first.
assert(deflated_count >= unlinked_count, "Sanity: underflow");
size_t unlinked_batch_limit = MIN2<size_t>(deflated_count - unlinked_count, MonitorUnlinkBatch);
do {
ObjectMonitor* next_next = next->next_om();
unlinked_batch++;
unlinked_list->append(next);
next = next_next;
if (unlinked_batch >= unlinked_batch_limit) {
// Reached the max batch, so bail out of the gathering loop.
break;
}
if (prev == nullptr && Atomic::load(&_head) != m) {
// Current batch used to be at head, but it is not at head anymore.
// Bail out and figure out where we currently are. This avoids long
// walks searching for new prev during unlink under heavy list inserts.
break;
}
} while (next != nullptr && next->is_being_async_deflated());
// Unlink the found batch.
if (prev == nullptr) {
// The current batch is the first batch, so there is a chance that it starts at head.
// Optimistically assume no inserts happened, and try to unlink the entire batch from the head.
ObjectMonitor* prev_head = Atomic::cmpxchg(&_head, m, next);
if (prev_head != m) {
// Something must have updated the head. Figure out the actual prev for this batch.
for (ObjectMonitor* n = prev_head; n != m; n = n->next_om()) {
prev = n;
}
assert(prev != nullptr, "Should have found the prev for the current batch");
prev->set_next_om(next);
}
} else {
// The current batch is preceded by another batch. This guarantees the current batch
// does not start at head. Unlink the entire current batch without updating the head.
assert(Atomic::load(&_head) != m, "Sanity");
prev->set_next_om(next);
}
unlinked_count += unlinked_batch;
if (unlinked_count >= deflated_count) {
// Reached the max so bail out of the searching loop.
// There should be no more deflated monitors left.
break;
}
m = next;
} else {
prev = m;
m = m->next_om();
}
// Must check for a safepoint/handshake and honor it.
safepointer->block_for_safepoint("unlinking", "unlinked_count", unlinked_count);
}
#ifdef ASSERT
// Invariant: the code above should unlink all deflated monitors.
// The code that runs after this unlinking does not expect deflated monitors.
// Notably, attempting to deflate the already deflated monitor would break.
{
ObjectMonitor* m = Atomic::load_acquire(&_head);
while (m != nullptr) {
assert(!m->is_being_async_deflated(), "All deflated monitors should be unlinked");
m = m->next_om();
}
}
#endif
Atomic::sub(&_count, unlinked_count);
return unlinked_count;
}
MonitorList::Iterator MonitorList::iterator() const {
return Iterator(Atomic::load_acquire(&_head));
}
ObjectMonitor* MonitorList::Iterator::next() {
ObjectMonitor* current = _current;
_current = current->next_om();
return current;
}
// The "core" versions of monitor enter and exit reside in this file.
// The interpreter and compilers contain specialized transliterated
// variants of the enter-exit fast-path operations. See c2_MacroAssembler_x86.cpp
// fast_lock(...) for instance. If you make changes here, make sure to modify the
// interpreter, and both C1 and C2 fast-path inline locking code emission.
//
// -----------------------------------------------------------------------------
#ifdef DTRACE_ENABLED
// Only bother with this argument setup if dtrace is available
// TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly.
#define DTRACE_MONITOR_PROBE_COMMON(obj, thread) \
char* bytes = nullptr; \
int len = 0; \
jlong jtid = SharedRuntime::get_java_tid(thread); \
Symbol* klassname = obj->klass()->name(); \
if (klassname != nullptr) { \
bytes = (char*)klassname->bytes(); \
len = klassname->utf8_length(); \
}
#define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis) \
{ \
if (DTraceMonitorProbes) { \
DTRACE_MONITOR_PROBE_COMMON(obj, thread); \
HOTSPOT_MONITOR_WAIT(jtid, \
(uintptr_t)(monitor), bytes, len, (millis)); \
} \
}
#define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY
#define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL
#define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED
#define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread) \
{ \
if (DTraceMonitorProbes) { \
DTRACE_MONITOR_PROBE_COMMON(obj, thread); \
HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */ \
(uintptr_t)(monitor), bytes, len); \
} \
}
#else // ndef DTRACE_ENABLED
#define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon) {;}
#define DTRACE_MONITOR_PROBE(probe, obj, thread, mon) {;}
#endif // ndef DTRACE_ENABLED
// This exists only as a workaround of dtrace bug 6254741
int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, JavaThread* thr) {
DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
return 0;
}
static constexpr size_t inflation_lock_count() {
return 256;
}
// Static storage for an array of PlatformMutex.
alignas(PlatformMutex) static uint8_t _inflation_locks[inflation_lock_count()][sizeof(PlatformMutex)];
static inline PlatformMutex* inflation_lock(size_t index) {
return reinterpret_cast<PlatformMutex*>(_inflation_locks[index]);
}
void ObjectSynchronizer::initialize() {
for (size_t i = 0; i < inflation_lock_count(); i++) {
::new(static_cast<void*>(inflation_lock(i))) PlatformMutex();
}
// Start the ceiling with the estimate for one thread.
set_in_use_list_ceiling(AvgMonitorsPerThreadEstimate);
// Start the timer for deflations, so it does not trigger immediately.
_last_async_deflation_time_ns = os::javaTimeNanos();
}
MonitorList ObjectSynchronizer::_in_use_list;
// monitors_used_above_threshold() policy is as follows:
//
// The ratio of the current _in_use_list count to the ceiling is used
// to determine if we are above MonitorUsedDeflationThreshold and need
// to do an async monitor deflation cycle. The ceiling is increased by
// AvgMonitorsPerThreadEstimate when a thread is added to the system
// and is decreased by AvgMonitorsPerThreadEstimate when a thread is
// removed from the system.
//
// Note: If the _in_use_list max exceeds the ceiling, then
// monitors_used_above_threshold() will use the in_use_list max instead
// of the thread count derived ceiling because we have used more
// ObjectMonitors than the estimated average.
//
// Note: If deflate_idle_monitors() has NoAsyncDeflationProgressMax
// no-progress async monitor deflation cycles in a row, then the ceiling
// is adjusted upwards by monitors_used_above_threshold().
//
// Start the ceiling with the estimate for one thread in initialize()
// which is called after cmd line options are processed.
static size_t _in_use_list_ceiling = 0;
bool volatile ObjectSynchronizer::_is_async_deflation_requested = false;
bool volatile ObjectSynchronizer::_is_final_audit = false;
jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0;
static uintx _no_progress_cnt = 0;
static bool _no_progress_skip_increment = false;
// =====================> Quick functions
// The quick_* forms are special fast-path variants used to improve
// performance. In the simplest case, a "quick_*" implementation could
// simply return false, in which case the caller will perform the necessary
// state transitions and call the slow-path form.
// The fast-path is designed to handle frequently arising cases in an efficient
// manner and is just a degenerate "optimistic" variant of the slow-path.
// returns true -- to indicate the call was satisfied.
// returns false -- to indicate the call needs the services of the slow-path.
// A no-loitering ordinance is in effect for code in the quick_* family
// operators: safepoints or indefinite blocking (blocking that might span a
// safepoint) are forbidden. Generally the thread_state() is _in_Java upon
// entry.
//
// Consider: An interesting optimization is to have the JIT recognize the
// following common idiom:
// synchronized (someobj) { .... ; notify(); }
// That is, we find a notify() or notifyAll() call that immediately precedes
// the monitorexit operation. In that case the JIT could fuse the operations
// into a single notifyAndExit() runtime primitive.
bool ObjectSynchronizer::quick_notify(oopDesc* obj, JavaThread* current, bool all) {
assert(current->thread_state() == _thread_in_Java, "invariant");
NoSafepointVerifier nsv;
if (obj == nullptr) return false; // slow-path for invalid obj
const markWord mark = obj->mark();
if (LockingMode == LM_LIGHTWEIGHT) {
if (mark.is_fast_locked() && current->lock_stack().contains(cast_to_oop(obj))) {
// Degenerate notify
// fast-locked by caller so by definition the implied waitset is empty.
return true;
}
} else if (LockingMode == LM_LEGACY) {
if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
// Degenerate notify
// stack-locked by caller so by definition the implied waitset is empty.
return true;
}
}
if (mark.has_monitor()) {
ObjectMonitor* const mon = mark.monitor();
assert(mon->object() == oop(obj), "invariant");
if (mon->owner() != current) return false; // slow-path for IMS exception
if (mon->first_waiter() != nullptr) {
// We have one or more waiters. Since this is an inflated monitor
// that we own, we can transfer one or more threads from the waitset
// to the entrylist here and now, avoiding the slow-path.
if (all) {
DTRACE_MONITOR_PROBE(notifyAll, mon, obj, current);
} else {
DTRACE_MONITOR_PROBE(notify, mon, obj, current);
}
int free_count = 0;
do {
mon->INotify(current);
++free_count;
} while (mon->first_waiter() != nullptr && all);
OM_PERFDATA_OP(Notifications, inc(free_count));
}
return true;
}
// other IMS exception states take the slow-path
return false;
}
// The LockNode emitted directly at the synchronization site would have
// been too big if it were to have included support for the cases of inflated
// recursive enter and exit, so they go here instead.
// Note that we can't safely call AsyncPrintJavaStack() from within
// quick_enter() as our thread state remains _in_Java.
bool ObjectSynchronizer::quick_enter(oop obj, JavaThread* current,
BasicLock * lock) {
assert(current->thread_state() == _thread_in_Java, "invariant");
NoSafepointVerifier nsv;
if (obj == nullptr) return false; // Need to throw NPE
if (obj->klass()->is_value_based()) {
return false;
}
const markWord mark = obj->mark();
if (mark.has_monitor()) {
ObjectMonitor* const m = mark.monitor();
// An async deflation or GC can race us before we manage to make
// the ObjectMonitor busy by setting the owner below. If we detect
// that race we just bail out to the slow-path here.
if (m->object_peek() == nullptr) {
return false;
}
JavaThread* const owner = static_cast<JavaThread*>(m->owner_raw());
// Lock contention and Transactional Lock Elision (TLE) diagnostics
// and observability
// Case: light contention possibly amenable to TLE
// Case: TLE inimical operations such as nested/recursive synchronization
if (owner == current) {
m->_recursions++;
current->inc_held_monitor_count();
return true;
}
if (LockingMode != LM_LIGHTWEIGHT) {
// This Java Monitor is inflated so obj's header will never be
// displaced to this thread's BasicLock. Make the displaced header
// non-null so this BasicLock is not seen as recursive nor as
// being locked. We do this unconditionally so that this thread's
// BasicLock cannot be mis-interpreted by any stack walkers. For
// performance reasons, stack walkers generally first check for
// stack-locking in the object's header, the second check is for
// recursive stack-locking in the displaced header in the BasicLock,
// and last are the inflated Java Monitor (ObjectMonitor) checks.
lock->set_displaced_header(markWord::unused_mark());
}
if (owner == nullptr && m->try_set_owner_from(nullptr, current) == nullptr) {
assert(m->_recursions == 0, "invariant");
current->inc_held_monitor_count();
return true;
}
}
// Note that we could inflate in quick_enter.
// This is likely a useful optimization
// Critically, in quick_enter() we must not:
// -- block indefinitely, or
// -- reach a safepoint
return false; // revert to slow-path
}
// Handle notifications when synchronizing on value based classes
void ObjectSynchronizer::handle_sync_on_value_based_class(Handle obj, JavaThread* current) {
frame last_frame = current->last_frame();
bool bcp_was_adjusted = false;
// Don't decrement bcp if it points to the frame's first instruction. This happens when
// handle_sync_on_value_based_class() is called because of a synchronized method. There
// is no actual monitorenter instruction in the byte code in this case.
if (last_frame.is_interpreted_frame() &&
(last_frame.interpreter_frame_method()->code_base() < last_frame.interpreter_frame_bcp())) {
// adjust bcp to point back to monitorenter so that we print the correct line numbers
last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() - 1);
bcp_was_adjusted = true;
}
if (DiagnoseSyncOnValueBasedClasses == FATAL_EXIT) {
ResourceMark rm(current);
stringStream ss;
current->print_active_stack_on(&ss);
char* base = (char*)strstr(ss.base(), "at");
char* newline = (char*)strchr(ss.base(), '\n');
if (newline != nullptr) {
*newline = '\0';
}
fatal("Synchronizing on object " INTPTR_FORMAT " of klass %s %s", p2i(obj()), obj->klass()->external_name(), base);
} else {
assert(DiagnoseSyncOnValueBasedClasses == LOG_WARNING, "invalid value for DiagnoseSyncOnValueBasedClasses");
ResourceMark rm(current);
Log(valuebasedclasses) vblog;
vblog.info("Synchronizing on object " INTPTR_FORMAT " of klass %s", p2i(obj()), obj->klass()->external_name());
if (current->has_last_Java_frame()) {
LogStream info_stream(vblog.info());
current->print_active_stack_on(&info_stream);
} else {
vblog.info("Cannot find the last Java frame");
}
EventSyncOnValueBasedClass event;
if (event.should_commit()) {
event.set_valueBasedClass(obj->klass());
event.commit();
}
}
if (bcp_was_adjusted) {
last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() + 1);
}
}
static bool useHeavyMonitors() {
#if defined(X86) || defined(AARCH64) || defined(PPC64) || defined(RISCV64) || defined(S390)
return LockingMode == LM_MONITOR;
#else
return false;
#endif
}
// -----------------------------------------------------------------------------
// Monitor Enter/Exit
// The interpreter and compiler assembly code tries to lock using the fast path
// of this algorithm. Make sure to update that code if the following function is
// changed. The implementation is extremely sensitive to race condition. Be careful.
void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) {
if (obj->klass()->is_value_based()) {
handle_sync_on_value_based_class(obj, current);
}
current->inc_held_monitor_count();
if (!useHeavyMonitors()) {
if (LockingMode == LM_LIGHTWEIGHT) {
// Fast-locking does not use the 'lock' argument.
LockStack& lock_stack = current->lock_stack();
if (lock_stack.can_push()) {
markWord mark = obj()->mark_acquire();
if (mark.is_neutral()) {
assert(!lock_stack.contains(obj()), "thread must not already hold the lock");
// Try to swing into 'fast-locked' state.
markWord locked_mark = mark.set_fast_locked();
markWord old_mark = obj()->cas_set_mark(locked_mark, mark);
if (old_mark == mark) {
// Successfully fast-locked, push object to lock-stack and return.
lock_stack.push(obj());
return;
}
}
}
// All other paths fall-through to inflate-enter.
} else if (LockingMode == LM_LEGACY) {
markWord mark = obj->mark();
if (mark.is_neutral()) {
// Anticipate successful CAS -- the ST of the displaced mark must
// be visible <= the ST performed by the CAS.
lock->set_displaced_header(mark);
if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) {
return;
}
// Fall through to inflate() ...
} else if (mark.has_locker() &&
current->is_lock_owned((address) mark.locker())) {
assert(lock != mark.locker(), "must not re-lock the same lock");
assert(lock != (BasicLock*) obj->mark().value(), "don't relock with same BasicLock");
lock->set_displaced_header(markWord::from_pointer(nullptr));
return;
}
// The object header will never be displaced to this lock,
// so it does not matter what the value is, except that it
// must be non-zero to avoid looking like a re-entrant lock,
// and must not look locked either.
lock->set_displaced_header(markWord::unused_mark());
}
} else if (VerifyHeavyMonitors) {
guarantee((obj->mark().value() & markWord::lock_mask_in_place) != markWord::locked_value, "must not be lightweight/stack-locked");
}
// An async deflation can race after the inflate() call and before
// enter() can make the ObjectMonitor busy. enter() returns false if
// we have lost the race to async deflation and we simply try again.
while (true) {
ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_monitor_enter);
if (monitor->enter(current)) {
return;
}
}
}
void ObjectSynchronizer::exit(oop object, BasicLock* lock, JavaThread* current) {
current->dec_held_monitor_count();
if (!useHeavyMonitors()) {
markWord mark = object->mark();
if (LockingMode == LM_LIGHTWEIGHT) {
// Fast-locking does not use the 'lock' argument.
if (mark.is_fast_locked()) {
markWord unlocked_mark = mark.set_unlocked();
markWord old_mark = object->cas_set_mark(unlocked_mark, mark);
if (old_mark != mark) {
// Another thread won the CAS, it must have inflated the monitor.
// It can only have installed an anonymously locked monitor at this point.
// Fetch that monitor, set owner correctly to this thread, and
// exit it (allowing waiting threads to enter).
assert(old_mark.has_monitor(), "must have monitor");
ObjectMonitor* monitor = old_mark.monitor();
assert(monitor->is_owner_anonymous(), "must be anonymous owner");
monitor->set_owner_from_anonymous(current);
monitor->exit(current);
}
LockStack& lock_stack = current->lock_stack();
lock_stack.remove(object);
return;
}
} else if (LockingMode == LM_LEGACY) {
markWord dhw = lock->displaced_header();
if (dhw.value() == 0) {
// If the displaced header is null, then this exit matches up with
// a recursive enter. No real work to do here except for diagnostics.
#ifndef PRODUCT
if (mark != markWord::INFLATING()) {
// Only do diagnostics if we are not racing an inflation. Simply
// exiting a recursive enter of a Java Monitor that is being
// inflated is safe; see the has_monitor() comment below.
assert(!mark.is_neutral(), "invariant");
assert(!mark.has_locker() ||
current->is_lock_owned((address)mark.locker()), "invariant");
if (mark.has_monitor()) {
// The BasicLock's displaced_header is marked as a recursive
// enter and we have an inflated Java Monitor (ObjectMonitor).
// This is a special case where the Java Monitor was inflated
// after this thread entered the stack-lock recursively. When a
// Java Monitor is inflated, we cannot safely walk the Java
// Monitor owner's stack and update the BasicLocks because a
// Java Monitor can be asynchronously inflated by a thread that
// does not own the Java Monitor.
ObjectMonitor* m = mark.monitor();
assert(m->object()->mark() == mark, "invariant");
assert(m->is_entered(current), "invariant");
}
}
#endif
return;
}
if (mark == markWord::from_pointer(lock)) {
// If the object is stack-locked by the current thread, try to
// swing the displaced header from the BasicLock back to the mark.
assert(dhw.is_neutral(), "invariant");
if (object->cas_set_mark(dhw, mark) == mark) {
return;
}
}
}
} else if (VerifyHeavyMonitors) {
guarantee((object->mark().value() & markWord::lock_mask_in_place) != markWord::locked_value, "must not be lightweight/stack-locked");
}
// We have to take the slow-path of possible inflation and then exit.
// The ObjectMonitor* can't be async deflated until ownership is
// dropped inside exit() and the ObjectMonitor* must be !is_busy().
ObjectMonitor* monitor = inflate(current, object, inflate_cause_vm_internal);
assert(!monitor->is_owner_anonymous(), "must not be");
monitor->exit(current);
}
// -----------------------------------------------------------------------------
// JNI locks on java objects
// NOTE: must use heavy weight monitor to handle jni monitor enter
void ObjectSynchronizer::jni_enter(Handle obj, JavaThread* current) {
if (obj->klass()->is_value_based()) {
handle_sync_on_value_based_class(obj, current);
}
// the current locking is from JNI instead of Java code
current->set_current_pending_monitor_is_from_java(false);
// An async deflation can race after the inflate() call and before
// enter() can make the ObjectMonitor busy. enter() returns false if
// we have lost the race to async deflation and we simply try again.
while (true) {
ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_jni_enter);
if (monitor->enter(current)) {
current->inc_held_monitor_count(1, true);
break;
}
}
current->set_current_pending_monitor_is_from_java(true);
}
// NOTE: must use heavy weight monitor to handle jni monitor exit
void ObjectSynchronizer::jni_exit(oop obj, TRAPS) {
JavaThread* current = THREAD;
// The ObjectMonitor* can't be async deflated until ownership is
// dropped inside exit() and the ObjectMonitor* must be !is_busy().
ObjectMonitor* monitor = inflate(current, obj, inflate_cause_jni_exit);
// If this thread has locked the object, exit the monitor. We
// intentionally do not use CHECK on check_owner because we must exit the
// monitor even if an exception was already pending.
if (monitor->check_owner(THREAD)) {
monitor->exit(current);
current->dec_held_monitor_count(1, true);
}
}
// -----------------------------------------------------------------------------
// Internal VM locks on java objects
// standard constructor, allows locking failures
ObjectLocker::ObjectLocker(Handle obj, JavaThread* thread) {
_thread = thread;
_thread->check_for_valid_safepoint_state();
_obj = obj;
if (_obj() != nullptr) {
ObjectSynchronizer::enter(_obj, &_lock, _thread);
}
}
ObjectLocker::~ObjectLocker() {
if (_obj() != nullptr) {
ObjectSynchronizer::exit(_obj(), &_lock, _thread);
}
}
// -----------------------------------------------------------------------------
// Wait/Notify/NotifyAll
// NOTE: must use heavy weight monitor to handle wait()
int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
JavaThread* current = THREAD;
if (millis < 0) {
THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
}
// The ObjectMonitor* can't be async deflated because the _waiters
// field is incremented before ownership is dropped and decremented
// after ownership is regained.
ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_wait);
DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), current, millis);
monitor->wait(millis, true, THREAD); // Not CHECK as we need following code
// This dummy call is in place to get around dtrace bug 6254741. Once
// that's fixed we can uncomment the following line, remove the call
// and change this function back into a "void" func.
// DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
return ret_code;
}
void ObjectSynchronizer::notify(Handle obj, TRAPS) {
JavaThread* current = THREAD;
markWord mark = obj->mark();
if (LockingMode == LM_LIGHTWEIGHT) {
if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
// Not inflated so there can't be any waiters to notify.
return;
}
} else if (LockingMode == LM_LEGACY) {
if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
// Not inflated so there can't be any waiters to notify.
return;
}
}
// The ObjectMonitor* can't be async deflated until ownership is
// dropped by the calling thread.
ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_notify);
monitor->notify(CHECK);
}
// NOTE: see comment of notify()
void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
JavaThread* current = THREAD;
markWord mark = obj->mark();
if (LockingMode == LM_LIGHTWEIGHT) {
if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
// Not inflated so there can't be any waiters to notify.
return;
}
} else if (LockingMode == LM_LEGACY) {
if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
// Not inflated so there can't be any waiters to notify.
return;
}
}
// The ObjectMonitor* can't be async deflated until ownership is
// dropped by the calling thread.
ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_notify);
monitor->notifyAll(CHECK);
}
// -----------------------------------------------------------------------------
// Hash Code handling
struct SharedGlobals {
char _pad_prefix[OM_CACHE_LINE_SIZE];
// This is a highly shared mostly-read variable.
// To avoid false-sharing it needs to be the sole occupant of a cache line.
volatile int stw_random;
DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int));
// Hot RW variable -- Sequester to avoid false-sharing
volatile int hc_sequence;
DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int));
};
static SharedGlobals GVars;
static markWord read_stable_mark(oop obj) {
markWord mark = obj->mark_acquire();
if (!mark.is_being_inflated() || LockingMode == LM_LIGHTWEIGHT) {
// New lightweight locking does not use the markWord::INFLATING() protocol.
return mark; // normal fast-path return
}
int its = 0;
for (;;) {
markWord mark = obj->mark_acquire();
if (!mark.is_being_inflated()) {
return mark; // normal fast-path return
}
// The object is being inflated by some other thread.
// The caller of read_stable_mark() must wait for inflation to complete.
// Avoid live-lock.
++its;
if (its > 10000 || !os::is_MP()) {
if (its & 1) {
os::naked_yield();
} else {
// Note that the following code attenuates the livelock problem but is not
// a complete remedy. A more complete solution would require that the inflating
// thread hold the associated inflation lock. The following code simply restricts
// the number of spinners to at most one. We'll have N-2 threads blocked
// on the inflationlock, 1 thread holding the inflation lock and using
// a yield/park strategy, and 1 thread in the midst of inflation.
// A more refined approach would be to change the encoding of INFLATING
// to allow encapsulation of a native thread pointer. Threads waiting for
// inflation to complete would use CAS to push themselves onto a singly linked
// list rooted at the markword. Once enqueued, they'd loop, checking a per-thread flag
// and calling park(). When inflation was complete the thread that accomplished inflation
// would detach the list and set the markword to inflated with a single CAS and
// then for each thread on the list, set the flag and unpark() the thread.
// Index into the lock array based on the current object address.
static_assert(is_power_of_2(inflation_lock_count()), "must be");
size_t ix = (cast_from_oop<intptr_t>(obj) >> 5) & (inflation_lock_count() - 1);
int YieldThenBlock = 0;
assert(ix < inflation_lock_count(), "invariant");
inflation_lock(ix)->lock();
while (obj->mark_acquire() == markWord::INFLATING()) {
// Beware: naked_yield() is advisory and has almost no effect on some platforms
// so we periodically call current->_ParkEvent->park(1).
// We use a mixed spin/yield/block mechanism.
if ((YieldThenBlock++) >= 16) {
Thread::current()->_ParkEvent->park(1);
} else {
os::naked_yield();
}
}
inflation_lock(ix)->unlock();
}
} else {
SpinPause(); // SMP-polite spinning
}
}
}
// hashCode() generation :
//
// Possibilities:
// * MD5Digest of {obj,stw_random}
// * CRC32 of {obj,stw_random} or any linear-feedback shift register function.
// * A DES- or AES-style SBox[] mechanism
// * One of the Phi-based schemes, such as:
// 2654435761 = 2^32 * Phi (golden ratio)
// HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ;
// * A variation of Marsaglia's shift-xor RNG scheme.
// * (obj ^ stw_random) is appealing, but can result
// in undesirable regularity in the hashCode values of adjacent objects
// (objects allocated back-to-back, in particular). This could potentially
// result in hashtable collisions and reduced hashtable efficiency.
// There are simple ways to "diffuse" the middle address bits over the
// generated hashCode values:
static inline intptr_t get_next_hash(Thread* current, oop obj) {
intptr_t value = 0;
if (hashCode == 0) {
// This form uses global Park-Miller RNG.
// On MP system we'll have lots of RW access to a global, so the
// mechanism induces lots of coherency traffic.
value = os::random();
} else if (hashCode == 1) {
// This variation has the property of being stable (idempotent)
// between STW operations. This can be useful in some of the 1-0
// synchronization schemes.
intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3;
value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random;
} else if (hashCode == 2) {
value = 1; // for sensitivity testing
} else if (hashCode == 3) {
value = ++GVars.hc_sequence;
} else if (hashCode == 4) {
value = cast_from_oop<intptr_t>(obj);
} else {
// Marsaglia's xor-shift scheme with thread-specific state
// This is probably the best overall implementation -- we'll
// likely make this the default in future releases.
unsigned t = current->_hashStateX;
t ^= (t << 11);
current->_hashStateX = current->_hashStateY;
current->_hashStateY = current->_hashStateZ;
current->_hashStateZ = current->_hashStateW;
unsigned v = current->_hashStateW;
v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
current->_hashStateW = v;
value = v;
}
value &= markWord::hash_mask;
if (value == 0) value = 0xBAD;
assert(value != markWord::no_hash, "invariant");
return value;
}
// Can be called from non JavaThreads (e.g., VMThread) for FastHashCode
// calculations as part of JVM/TI tagging.
static bool is_lock_owned(Thread* thread, oop obj) {
assert(LockingMode == LM_LIGHTWEIGHT, "only call this with new lightweight locking enabled");
return thread->is_Java_thread() ? JavaThread::cast(thread)->lock_stack().contains(obj) : false;
}
intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) {
while (true) {
ObjectMonitor* monitor = nullptr;
markWord temp, test;
intptr_t hash;
markWord mark = read_stable_mark(obj);
if (VerifyHeavyMonitors) {
assert(LockingMode == LM_MONITOR, "+VerifyHeavyMonitors requires LockingMode == 0 (LM_MONITOR)");
guarantee((obj->mark().value() & markWord::lock_mask_in_place) != markWord::locked_value, "must not be lightweight/stack-locked");
}
if (mark.is_neutral()) { // if this is a normal header
hash = mark.hash();
if (hash != 0) { // if it has a hash, just return it
return hash;
}
hash = get_next_hash(current, obj); // get a new hash
temp = mark.copy_set_hash(hash); // merge the hash into header
// try to install the hash
test = obj->cas_set_mark(temp, mark);
if (test == mark) { // if the hash was installed, return it
return hash;
}
// Failed to install the hash. It could be that another thread
// installed the hash just before our attempt or inflation has
// occurred or... so we fall thru to inflate the monitor for
// stability and then install the hash.
} else if (mark.has_monitor()) {
monitor = mark.monitor();
temp = monitor->header();
assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
hash = temp.hash();
if (hash != 0) {
// It has a hash.
// Separate load of dmw/header above from the loads in
// is_being_async_deflated().
// dmw/header and _contentions may get written by different threads.
// Make sure to observe them in the same order when having several observers.
OrderAccess::loadload_for_IRIW();
if (monitor->is_being_async_deflated()) {
// But we can't safely use the hash if we detect that async
// deflation has occurred. So we attempt to restore the
// header/dmw to the object's header so that we only retry
// once if the deflater thread happens to be slow.
monitor->install_displaced_markword_in_object(obj);
continue;
}
return hash;
}
// Fall thru so we only have one place that installs the hash in
// the ObjectMonitor.
} else if (LockingMode == LM_LIGHTWEIGHT && mark.is_fast_locked() && is_lock_owned(current, obj)) {
// This is a fast-lock owned by the calling thread so use the
// markWord from the object.
hash = mark.hash();
if (hash != 0) { // if it has a hash, just return it
return hash;
}
} else if (LockingMode == LM_LEGACY && mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
// This is a stack-lock owned by the calling thread so fetch the
// displaced markWord from the BasicLock on the stack.
temp = mark.displaced_mark_helper();
assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
hash = temp.hash();
if (hash != 0) { // if it has a hash, just return it
return hash;
}
// WARNING:
// The displaced header in the BasicLock on a thread's stack
// is strictly immutable. It CANNOT be changed in ANY cases.
// So we have to inflate the stack-lock into an ObjectMonitor
// even if the current thread owns the lock. The BasicLock on
// a thread's stack can be asynchronously read by other threads
// during an inflate() call so any change to that stack memory
// may not propagate to other threads correctly.
}
// Inflate the monitor to set the hash.
// An async deflation can race after the inflate() call and before we