-
Notifications
You must be signed in to change notification settings - Fork 1k
/
thread.cpp
4948 lines (4232 loc) · 175 KB
/
thread.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) 1997, 2018, 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 "jvm.h"
#include "classfile/classLoader.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/moduleEntry.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "code/codeCache.hpp"
#include "code/scopeDesc.hpp"
#include "compiler/compileBroker.hpp"
#include "compiler/compileTask.hpp"
#include "gc/shared/barrierSet.hpp"
#include "gc/shared/gcId.hpp"
#include "gc/shared/gcLocker.inline.hpp"
#include "gc/shared/workgroup.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/linkResolver.hpp"
#include "interpreter/oopMapCache.hpp"
#include "jfr/jfrEvents.hpp"
#include "jfr/support/jfrThreadId.hpp"
#include "jvmtifiles/jvmtiEnv.hpp"
#include "logging/log.hpp"
#include "logging/logConfiguration.hpp"
#include "logging/logStream.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/metaspaceShared.hpp"
#include "memory/oopFactory.hpp"
#include "memory/resourceArea.hpp"
#include "memory/universe.hpp"
#include "oops/access.inline.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/objArrayOop.hpp"
#include "oops/oop.inline.hpp"
#include "oops/symbol.hpp"
#include "oops/typeArrayOop.inline.hpp"
#include "oops/verifyOopClosure.hpp"
#include "prims/jvm_misc.hpp"
#include "prims/jvmtiExport.hpp"
#include "prims/jvmtiThreadState.hpp"
#include "prims/privilegedStack.hpp"
#include "runtime/arguments.hpp"
#include "runtime/atomic.hpp"
#include "runtime/biasedLocking.hpp"
#include "runtime/flags/jvmFlagConstraintList.hpp"
#include "runtime/flags/jvmFlagRangeList.hpp"
#include "runtime/flags/jvmFlagWriteableList.hpp"
#include "runtime/deoptimization.hpp"
#include "runtime/frame.inline.hpp"
#include "runtime/handshake.hpp"
#include "runtime/init.hpp"
#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/jniHandles.inline.hpp"
#include "runtime/jniPeriodicChecker.hpp"
#include "runtime/memprofiler.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/objectMonitor.hpp"
#include "runtime/orderAccess.hpp"
#include "runtime/osThread.hpp"
#include "runtime/prefetch.inline.hpp"
#include "runtime/safepoint.hpp"
#include "runtime/safepointMechanism.inline.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/statSampler.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/sweeper.hpp"
#include "runtime/task.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/threadCritical.hpp"
#include "runtime/threadSMR.inline.hpp"
#include "runtime/timer.hpp"
#include "runtime/timerTrace.hpp"
#include "runtime/vframe.inline.hpp"
#include "runtime/vframeArray.hpp"
#include "runtime/vframe_hp.hpp"
#include "runtime/vmThread.hpp"
#include "runtime/vm_operations.hpp"
#include "runtime/vm_version.hpp"
#include "services/attachListener.hpp"
#include "services/management.hpp"
#include "services/memTracker.hpp"
#include "services/threadService.hpp"
#include "utilities/align.hpp"
#include "utilities/copy.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/dtrace.hpp"
#include "utilities/events.hpp"
#include "utilities/macros.hpp"
#include "utilities/preserveException.hpp"
#include "utilities/vmError.hpp"
#if INCLUDE_JVMCI
#include "jvmci/jvmciCompiler.hpp"
#include "jvmci/jvmciRuntime.hpp"
#include "logging/logHandle.hpp"
#endif
#ifdef COMPILER1
#include "c1/c1_Compiler.hpp"
#endif
#ifdef COMPILER2
#include "opto/c2compiler.hpp"
#include "opto/idealGraphPrinter.hpp"
#endif
#if INCLUDE_RTM_OPT
#include "runtime/rtmLocking.hpp"
#endif
#if INCLUDE_JFR
#include "jfr/jfr.hpp"
#endif
// Initialization after module runtime initialization
void universe_post_module_init(); // must happen after call_initPhase2
#ifdef DTRACE_ENABLED
// Only bother with this argument setup if dtrace is available
#define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
#define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
#define DTRACE_THREAD_PROBE(probe, javathread) \
{ \
ResourceMark rm(this); \
int len = 0; \
const char* name = (javathread)->get_thread_name(); \
len = strlen(name); \
HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */ \
(char *) name, len, \
java_lang_Thread::thread_id((javathread)->threadObj()), \
(uintptr_t) (javathread)->osthread()->thread_id(), \
java_lang_Thread::is_daemon((javathread)->threadObj())); \
}
#else // ndef DTRACE_ENABLED
#define DTRACE_THREAD_PROBE(probe, javathread)
#endif // ndef DTRACE_ENABLED
#ifndef USE_LIBRARY_BASED_TLS_ONLY
// Current thread is maintained as a thread-local variable
THREAD_LOCAL_DECL Thread* Thread::_thr_current = NULL;
#endif
// Class hierarchy
// - Thread
// - VMThread
// - WatcherThread
// - ConcurrentMarkSweepThread
// - JavaThread
// - CompilerThread
// ======= Thread ========
// Support for forcing alignment of thread objects for biased locking
void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
if (UseBiasedLocking) {
const int alignment = markOopDesc::biased_lock_alignment;
size_t aligned_size = size + (alignment - sizeof(intptr_t));
void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC)
: AllocateHeap(aligned_size, flags, CURRENT_PC,
AllocFailStrategy::RETURN_NULL);
void* aligned_addr = align_up(real_malloc_addr, alignment);
assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
"JavaThread alignment code overflowed allocated storage");
if (aligned_addr != real_malloc_addr) {
log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
p2i(real_malloc_addr),
p2i(aligned_addr));
}
((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
return aligned_addr;
} else {
return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
: AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
}
}
void Thread::operator delete(void* p) {
if (UseBiasedLocking) {
FreeHeap(((Thread*) p)->_real_malloc_address);
} else {
FreeHeap(p);
}
}
void JavaThread::smr_delete() {
if (_on_thread_list) {
ThreadsSMRSupport::smr_delete(this);
} else {
delete this;
}
}
// Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
// JavaThread
Thread::Thread() {
// stack and get_thread
set_stack_base(NULL);
set_stack_size(0);
set_self_raw_id(0);
set_lgrp_id(-1);
DEBUG_ONLY(clear_suspendible_thread();)
// allocated data structures
set_osthread(NULL);
set_resource_area(new (mtThread)ResourceArea());
DEBUG_ONLY(_current_resource_mark = NULL;)
set_handle_area(new (mtThread) HandleArea(NULL));
set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
set_active_handles(NULL);
set_free_handle_block(NULL);
set_last_handle_mark(NULL);
// This initial value ==> never claimed.
_oops_do_parity = 0;
_threads_hazard_ptr = NULL;
_threads_list_ptr = NULL;
_nested_threads_hazard_ptr_cnt = 0;
_rcu_counter = 0;
// the handle mark links itself to last_handle_mark
new HandleMark(this);
// plain initialization
debug_only(_owned_locks = NULL;)
debug_only(_allow_allocation_count = 0;)
NOT_PRODUCT(_allow_safepoint_count = 0;)
NOT_PRODUCT(_skip_gcalot = false;)
_jvmti_env_iteration_count = 0;
set_allocated_bytes(0);
_vm_operation_started_count = 0;
_vm_operation_completed_count = 0;
_current_pending_monitor = NULL;
_current_pending_monitor_is_from_java = true;
_current_waiting_monitor = NULL;
_num_nested_signal = 0;
omFreeList = NULL;
omFreeCount = 0;
omFreeProvision = 32;
omInUseList = NULL;
omInUseCount = 0;
#ifdef ASSERT
_visited_for_critical_count = false;
#endif
_SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true,
Monitor::_safepoint_check_sometimes);
_suspend_flags = 0;
// thread-specific hashCode stream generator state - Marsaglia shift-xor form
_hashStateX = os::random();
_hashStateY = 842502087;
_hashStateZ = 0x8767; // (int)(3579807591LL & 0xffff) ;
_hashStateW = 273326509;
_OnTrap = 0;
_schedctl = NULL;
_Stalled = 0;
_TypeTag = 0x2BAD;
// Many of the following fields are effectively final - immutable
// Note that nascent threads can't use the Native Monitor-Mutex
// construct until the _MutexEvent is initialized ...
// CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
// we might instead use a stack of ParkEvents that we could provision on-demand.
// The stack would act as a cache to avoid calls to ParkEvent::Allocate()
// and ::Release()
_ParkEvent = ParkEvent::Allocate(this);
_SleepEvent = ParkEvent::Allocate(this);
_MutexEvent = ParkEvent::Allocate(this);
_MuxEvent = ParkEvent::Allocate(this);
#ifdef CHECK_UNHANDLED_OOPS
if (CheckUnhandledOops) {
_unhandled_oops = new UnhandledOops(this);
}
#endif // CHECK_UNHANDLED_OOPS
#ifdef ASSERT
if (UseBiasedLocking) {
assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
assert(this == _real_malloc_address ||
this == align_up(_real_malloc_address, (int)markOopDesc::biased_lock_alignment),
"bug in forced alignment of thread objects");
}
#endif // ASSERT
// Notify the barrier set that a thread is being created. Note that the
// main thread is created before a barrier set is available. The call to
// BarrierSet::on_thread_create() for the main thread is therefore deferred
// until it calls BarrierSet::set_barrier_set().
BarrierSet* const barrier_set = BarrierSet::barrier_set();
if (barrier_set != NULL) {
barrier_set->on_thread_create(this);
}
}
void Thread::initialize_thread_current() {
#ifndef USE_LIBRARY_BASED_TLS_ONLY
assert(_thr_current == NULL, "Thread::current already initialized");
_thr_current = this;
#endif
assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized");
ThreadLocalStorage::set_thread(this);
assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
}
void Thread::clear_thread_current() {
assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
#ifndef USE_LIBRARY_BASED_TLS_ONLY
_thr_current = NULL;
#endif
ThreadLocalStorage::set_thread(NULL);
}
void Thread::record_stack_base_and_size() {
set_stack_base(os::current_stack_base());
set_stack_size(os::current_stack_size());
// CR 7190089: on Solaris, primordial thread's stack is adjusted
// in initialize_thread(). Without the adjustment, stack size is
// incorrect if stack is set to unlimited (ulimit -s unlimited).
// So far, only Solaris has real implementation of initialize_thread().
//
// set up any platform-specific state.
os::initialize_thread(this);
// Set stack limits after thread is initialized.
if (is_Java_thread()) {
((JavaThread*) this)->set_stack_overflow_limit();
((JavaThread*) this)->set_reserved_stack_activation(stack_base());
}
#if INCLUDE_NMT
// record thread's native stack, stack grows downward
MemTracker::record_thread_stack(stack_end(), stack_size());
#endif // INCLUDE_NMT
log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: "
PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).",
os::current_thread_id(), p2i(stack_base() - stack_size()),
p2i(stack_base()), stack_size()/1024);
}
Thread::~Thread() {
JFR_ONLY(Jfr::on_thread_destruct(this);)
// Notify the barrier set that a thread is being destroyed. Note that a barrier
// set might not be available if we encountered errors during bootstrapping.
BarrierSet* const barrier_set = BarrierSet::barrier_set();
if (barrier_set != NULL) {
barrier_set->on_thread_destroy(this);
}
// stack_base can be NULL if the thread is never started or exited before
// record_stack_base_and_size called. Although, we would like to ensure
// that all started threads do call record_stack_base_and_size(), there is
// not proper way to enforce that.
#if INCLUDE_NMT
if (_stack_base != NULL) {
MemTracker::release_thread_stack(stack_end(), stack_size());
#ifdef ASSERT
set_stack_base(NULL);
#endif
}
#endif // INCLUDE_NMT
// deallocate data structures
delete resource_area();
// since the handle marks are using the handle area, we have to deallocated the root
// handle mark before deallocating the thread's handle area,
assert(last_handle_mark() != NULL, "check we have an element");
delete last_handle_mark();
assert(last_handle_mark() == NULL, "check we have reached the end");
// It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
// We NULL out the fields for good hygiene.
ParkEvent::Release(_ParkEvent); _ParkEvent = NULL;
ParkEvent::Release(_SleepEvent); _SleepEvent = NULL;
ParkEvent::Release(_MutexEvent); _MutexEvent = NULL;
ParkEvent::Release(_MuxEvent); _MuxEvent = NULL;
delete handle_area();
delete metadata_handles();
// SR_handler uses this as a termination indicator -
// needs to happen before os::free_thread()
delete _SR_lock;
_SR_lock = NULL;
// osthread() can be NULL, if creation of thread failed.
if (osthread() != NULL) os::free_thread(osthread());
// clear Thread::current if thread is deleting itself.
// Needed to ensure JNI correctly detects non-attached threads.
if (this == Thread::current()) {
clear_thread_current();
}
CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
}
// NOTE: dummy function for assertion purpose.
void Thread::run() {
ShouldNotReachHere();
}
#ifdef ASSERT
// A JavaThread is considered "dangling" if it is not the current
// thread, has been added the Threads list, the system is not at a
// safepoint and the Thread is not "protected".
//
void Thread::check_for_dangling_thread_pointer(Thread *thread) {
assert(!thread->is_Java_thread() || Thread::current() == thread ||
!((JavaThread *) thread)->on_thread_list() ||
SafepointSynchronize::is_at_safepoint() ||
ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread),
"possibility of dangling Thread pointer");
}
#endif
ThreadPriority Thread::get_priority(const Thread* const thread) {
ThreadPriority priority;
// Can return an error!
(void)os::get_priority(thread, priority);
assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
return priority;
}
void Thread::set_priority(Thread* thread, ThreadPriority priority) {
debug_only(check_for_dangling_thread_pointer(thread);)
// Can return an error!
(void)os::set_priority(thread, priority);
}
void Thread::start(Thread* thread) {
// Start is different from resume in that its safety is guaranteed by context or
// being called from a Java method synchronized on the Thread object.
if (!DisableStartThread) {
if (thread->is_Java_thread()) {
// Initialize the thread state to RUNNABLE before starting this thread.
// Can not set it after the thread started because we do not know the
// exact thread state at that time. It could be in MONITOR_WAIT or
// in SLEEPING or some other state.
java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
java_lang_Thread::RUNNABLE);
}
os::start_thread(thread);
}
}
// Enqueue a VM_Operation to do the job for us - sometime later
void Thread::send_async_exception(oop java_thread, oop java_throwable) {
VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable);
VMThread::execute(vm_stop);
}
// Check if an external suspend request has completed (or has been
// cancelled). Returns true if the thread is externally suspended and
// false otherwise.
//
// The bits parameter returns information about the code path through
// the routine. Useful for debugging:
//
// set in is_ext_suspend_completed():
// 0x00000001 - routine was entered
// 0x00000010 - routine return false at end
// 0x00000100 - thread exited (return false)
// 0x00000200 - suspend request cancelled (return false)
// 0x00000400 - thread suspended (return true)
// 0x00001000 - thread is in a suspend equivalent state (return true)
// 0x00002000 - thread is native and walkable (return true)
// 0x00004000 - thread is native_trans and walkable (needed retry)
//
// set in wait_for_ext_suspend_completion():
// 0x00010000 - routine was entered
// 0x00020000 - suspend request cancelled before loop (return false)
// 0x00040000 - thread suspended before loop (return true)
// 0x00080000 - suspend request cancelled in loop (return false)
// 0x00100000 - thread suspended in loop (return true)
// 0x00200000 - suspend not completed during retry loop (return false)
// Helper class for tracing suspend wait debug bits.
//
// 0x00000100 indicates that the target thread exited before it could
// self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
// 0x00080000 each indicate a cancelled suspend request so they don't
// count as wait failures either.
#define DEBUG_FALSE_BITS (0x00000010 | 0x00200000)
class TraceSuspendDebugBits : public StackObj {
private:
JavaThread * jt;
bool is_wait;
bool called_by_wait; // meaningful when !is_wait
uint32_t * bits;
public:
TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait,
uint32_t *_bits) {
jt = _jt;
is_wait = _is_wait;
called_by_wait = _called_by_wait;
bits = _bits;
}
~TraceSuspendDebugBits() {
if (!is_wait) {
#if 1
// By default, don't trace bits for is_ext_suspend_completed() calls.
// That trace is very chatty.
return;
#else
if (!called_by_wait) {
// If tracing for is_ext_suspend_completed() is enabled, then only
// trace calls to it from wait_for_ext_suspend_completion()
return;
}
#endif
}
if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) {
if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) {
MutexLocker ml(Threads_lock); // needed for get_thread_name()
ResourceMark rm;
tty->print_cr(
"Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
jt->get_thread_name(), *bits);
guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed");
}
}
}
};
#undef DEBUG_FALSE_BITS
bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay,
uint32_t *bits) {
TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
bool did_trans_retry = false; // only do thread_in_native_trans retry once
bool do_trans_retry; // flag to force the retry
*bits |= 0x00000001;
do {
do_trans_retry = false;
if (is_exiting()) {
// Thread is in the process of exiting. This is always checked
// first to reduce the risk of dereferencing a freed JavaThread.
*bits |= 0x00000100;
return false;
}
if (!is_external_suspend()) {
// Suspend request is cancelled. This is always checked before
// is_ext_suspended() to reduce the risk of a rogue resume
// confusing the thread that made the suspend request.
*bits |= 0x00000200;
return false;
}
if (is_ext_suspended()) {
// thread is suspended
*bits |= 0x00000400;
return true;
}
// Now that we no longer do hard suspends of threads running
// native code, the target thread can be changing thread state
// while we are in this routine:
//
// _thread_in_native -> _thread_in_native_trans -> _thread_blocked
//
// We save a copy of the thread state as observed at this moment
// and make our decision about suspend completeness based on the
// copy. This closes the race where the thread state is seen as
// _thread_in_native_trans in the if-thread_blocked check, but is
// seen as _thread_blocked in if-thread_in_native_trans check.
JavaThreadState save_state = thread_state();
if (save_state == _thread_blocked && is_suspend_equivalent()) {
// If the thread's state is _thread_blocked and this blocking
// condition is known to be equivalent to a suspend, then we can
// consider the thread to be externally suspended. This means that
// the code that sets _thread_blocked has been modified to do
// self-suspension if the blocking condition releases. We also
// used to check for CONDVAR_WAIT here, but that is now covered by
// the _thread_blocked with self-suspension check.
//
// Return true since we wouldn't be here unless there was still an
// external suspend request.
*bits |= 0x00001000;
return true;
} else if (save_state == _thread_in_native && frame_anchor()->walkable()) {
// Threads running native code will self-suspend on native==>VM/Java
// transitions. If its stack is walkable (should always be the case
// unless this function is called before the actual java_suspend()
// call), then the wait is done.
*bits |= 0x00002000;
return true;
} else if (!called_by_wait && !did_trans_retry &&
save_state == _thread_in_native_trans &&
frame_anchor()->walkable()) {
// The thread is transitioning from thread_in_native to another
// thread state. check_safepoint_and_suspend_for_native_trans()
// will force the thread to self-suspend. If it hasn't gotten
// there yet we may have caught the thread in-between the native
// code check above and the self-suspend. Lucky us. If we were
// called by wait_for_ext_suspend_completion(), then it
// will be doing the retries so we don't have to.
//
// Since we use the saved thread state in the if-statement above,
// there is a chance that the thread has already transitioned to
// _thread_blocked by the time we get here. In that case, we will
// make a single unnecessary pass through the logic below. This
// doesn't hurt anything since we still do the trans retry.
*bits |= 0x00004000;
// Once the thread leaves thread_in_native_trans for another
// thread state, we break out of this retry loop. We shouldn't
// need this flag to prevent us from getting back here, but
// sometimes paranoia is good.
did_trans_retry = true;
// We wait for the thread to transition to a more usable state.
for (int i = 1; i <= SuspendRetryCount; i++) {
// We used to do an "os::yield_all(i)" call here with the intention
// that yielding would increase on each retry. However, the parameter
// is ignored on Linux which means the yield didn't scale up. Waiting
// on the SR_lock below provides a much more predictable scale up for
// the delay. It also provides a simple/direct point to check for any
// safepoint requests from the VMThread
// temporarily drops SR_lock while doing wait with safepoint check
// (if we're a JavaThread - the WatcherThread can also call this)
// and increase delay with each retry
SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
// check the actual thread state instead of what we saved above
if (thread_state() != _thread_in_native_trans) {
// the thread has transitioned to another thread state so
// try all the checks (except this one) one more time.
do_trans_retry = true;
break;
}
} // end retry loop
}
} while (do_trans_retry);
*bits |= 0x00000010;
return false;
}
// Wait for an external suspend request to complete (or be cancelled).
// Returns true if the thread is externally suspended and false otherwise.
//
bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
uint32_t *bits) {
TraceSuspendDebugBits tsdb(this, true /* is_wait */,
false /* !called_by_wait */, bits);
// local flag copies to minimize SR_lock hold time
bool is_suspended;
bool pending;
uint32_t reset_bits;
// set a marker so is_ext_suspend_completed() knows we are the caller
*bits |= 0x00010000;
// We use reset_bits to reinitialize the bits value at the top of
// each retry loop. This allows the caller to make use of any
// unused bits for their own marking purposes.
reset_bits = *bits;
{
MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
delay, bits);
pending = is_external_suspend();
}
// must release SR_lock to allow suspension to complete
if (!pending) {
// A cancelled suspend request is the only false return from
// is_ext_suspend_completed() that keeps us from entering the
// retry loop.
*bits |= 0x00020000;
return false;
}
if (is_suspended) {
*bits |= 0x00040000;
return true;
}
for (int i = 1; i <= retries; i++) {
*bits = reset_bits; // reinit to only track last retry
// We used to do an "os::yield_all(i)" call here with the intention
// that yielding would increase on each retry. However, the parameter
// is ignored on Linux which means the yield didn't scale up. Waiting
// on the SR_lock below provides a much more predictable scale up for
// the delay. It also provides a simple/direct point to check for any
// safepoint requests from the VMThread
{
MutexLocker ml(SR_lock());
// wait with safepoint check (if we're a JavaThread - the WatcherThread
// can also call this) and increase delay with each retry
SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
delay, bits);
// It is possible for the external suspend request to be cancelled
// (by a resume) before the actual suspend operation is completed.
// Refresh our local copy to see if we still need to wait.
pending = is_external_suspend();
}
if (!pending) {
// A cancelled suspend request is the only false return from
// is_ext_suspend_completed() that keeps us from staying in the
// retry loop.
*bits |= 0x00080000;
return false;
}
if (is_suspended) {
*bits |= 0x00100000;
return true;
}
} // end retry loop
// thread did not suspend after all our retries
*bits |= 0x00200000;
return false;
}
// Called from API entry points which perform stack walking. If the
// associated JavaThread is the current thread, then wait_for_suspend
// is not used. Otherwise, it determines if we should wait for the
// "other" thread to complete external suspension. (NOTE: in future
// releases the suspension mechanism should be reimplemented so this
// is not necessary.)
//
bool
JavaThread::is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits) {
if (this != JavaThread::current()) {
// "other" threads require special handling.
if (wait_for_suspend) {
// We are allowed to wait for the external suspend to complete
// so give the other thread a chance to get suspended.
if (!wait_for_ext_suspend_completion(SuspendRetryCount,
SuspendRetryDelay, bits)) {
// Didn't make it so let the caller know.
return false;
}
}
// We aren't allowed to wait for the external suspend to complete
// so if the other thread isn't externally suspended we need to
// let the caller know.
else if (!is_ext_suspend_completed_with_lock(bits)) {
return false;
}
}
return true;
}
#ifndef PRODUCT
void JavaThread::record_jump(address target, address instr, const char* file,
int line) {
// This should not need to be atomic as the only way for simultaneous
// updates is via interrupts. Even then this should be rare or non-existent
// and we don't care that much anyway.
int index = _jmp_ring_index;
_jmp_ring_index = (index + 1) & (jump_ring_buffer_size - 1);
_jmp_ring[index]._target = (intptr_t) target;
_jmp_ring[index]._instruction = (intptr_t) instr;
_jmp_ring[index]._file = file;
_jmp_ring[index]._line = line;
}
#endif // PRODUCT
void Thread::interrupt(Thread* thread) {
debug_only(check_for_dangling_thread_pointer(thread);)
os::interrupt(thread);
}
bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) {
debug_only(check_for_dangling_thread_pointer(thread);)
// Note: If clear_interrupted==false, this simply fetches and
// returns the value of the field osthread()->interrupted().
return os::is_interrupted(thread, clear_interrupted);
}
// GC Support
bool Thread::claim_oops_do_par_case(int strong_roots_parity) {
int thread_parity = _oops_do_parity;
if (thread_parity != strong_roots_parity) {
jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity);
if (res == thread_parity) {
return true;
} else {
guarantee(res == strong_roots_parity, "Or else what?");
return false;
}
}
return false;
}
void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
active_handles()->oops_do(f);
// Do oop for ThreadShadow
f->do_oop((oop*)&_pending_exception);
handle_area()->oops_do(f);
if (MonitorInUseLists) {
// When using thread local monitor lists, we scan them here,
// and the remaining global monitors in ObjectSynchronizer::oops_do().
ObjectSynchronizer::thread_local_used_oops_do(this, f);
}
}
void Thread::metadata_handles_do(void f(Metadata*)) {
// Only walk the Handles in Thread.
if (metadata_handles() != NULL) {
for (int i = 0; i< metadata_handles()->length(); i++) {
f(metadata_handles()->at(i));
}
}
}
void Thread::print_on(outputStream* st) const {
// get_priority assumes osthread initialized
if (osthread() != NULL) {
int os_prio;
if (os::get_native_priority(this, &os_prio) == OS_OK) {
st->print("os_prio=%d ", os_prio);
}
st->print("tid=" INTPTR_FORMAT " ", p2i(this));
osthread()->print_on(st);
}
ThreadsSMRSupport::print_info_on(this, st);
st->print(" ");
debug_only(if (WizardMode) print_owned_locks_on(st);)
}
// Thread::print_on_error() is called by fatal error handler. Don't use
// any lock or allocate memory.
void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates");
if (is_VM_thread()) { st->print("VMThread"); }
else if (is_GC_task_thread()) { st->print("GCTaskThread"); }
else if (is_Watcher_thread()) { st->print("WatcherThread"); }
else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); }
else { st->print("Thread"); }
if (is_Named_thread()) {
st->print(" \"%s\"", name());
}
st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
p2i(stack_end()), p2i(stack_base()));
if (osthread()) {
st->print(" [id=%d]", osthread()->thread_id());
}
ThreadsSMRSupport::print_info_on(this, st);
}
void Thread::print_value_on(outputStream* st) const {
if (is_Named_thread()) {
st->print(" \"%s\" ", name());
}
st->print(INTPTR_FORMAT, p2i(this)); // print address
}
#ifdef ASSERT
void Thread::print_owned_locks_on(outputStream* st) const {
Monitor *cur = _owned_locks;
if (cur == NULL) {
st->print(" (no locks) ");
} else {
st->print_cr(" Locks owned:");
while (cur) {
cur->print_on(st);
cur = cur->next();
}
}
}
static int ref_use_count = 0;
bool Thread::owns_locks_but_compiled_lock() const {
for (Monitor *cur = _owned_locks; cur; cur = cur->next()) {
if (cur != Compile_lock) return true;
}
return false;
}
#endif
#ifndef PRODUCT
// The flag: potential_vm_operation notifies if this particular safepoint state could potentially
// invoke the vm-thread (e.g., an oop allocation). In that case, we also have to make sure that
// no threads which allow_vm_block's are held
void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
// Check if current thread is allowed to block at a safepoint
if (!(_allow_safepoint_count == 0)) {
fatal("Possible safepoint reached by thread that does not allow it");
}
if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
fatal("LEAF method calling lock?");
}
#ifdef ASSERT
if (potential_vm_operation && is_Java_thread()
&& !Universe::is_bootstrapping()) {
// Make sure we do not hold any locks that the VM thread also uses.
// This could potentially lead to deadlocks
for (Monitor *cur = _owned_locks; cur; cur = cur->next()) {
// Threads_lock is special, since the safepoint synchronization will not start before this is
// acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock,
// since it is used to transfer control between JavaThreads and the VMThread
// Do not *exclude* any locks unless you are absolutely sure it is correct. Ask someone else first!
if ((cur->allow_vm_block() &&
cur != Threads_lock &&
cur != Compile_lock && // Temporary: should not be necessary when we get separate compilation
cur != VMOperationRequest_lock &&
cur != VMOperationQueue_lock) ||
cur->rank() == Mutex::special) {
fatal("Thread holding lock at safepoint that vm can block on: %s", cur->name());
}
}
}
if (GCALotAtAllSafepoints) {
// We could enter a safepoint here and thus have a gc
InterfaceSupport::check_gc_alot();
}
#endif
}
#endif
bool Thread::is_in_stack(address adr) const {
assert(Thread::current() == this, "is_in_stack can only be called from current thread");
address end = os::current_stack_pointer();
// Allow non Java threads to call this without stack_base
if (_stack_base == NULL) return true;
if (stack_base() >= adr && adr >= end) return true;
return false;
}
bool Thread::is_in_usable_stack(address adr) const {
size_t stack_guard_size = os::uses_stack_guard_pages() ? JavaThread::stack_guard_zone_size() : 0;
size_t usable_stack_size = _stack_size - stack_guard_size;