53 #include "oops/symbol.hpp"
54 #include "oops/verifyOopClosure.hpp"
55 #include "prims/jvm_misc.hpp"
56 #include "prims/jvmtiExport.hpp"
57 #include "prims/jvmtiThreadState.hpp"
58 #include "prims/privilegedStack.hpp"
59 #include "runtime/arguments.hpp"
60 #include "runtime/atomic.hpp"
61 #include "runtime/biasedLocking.hpp"
62 #include "runtime/commandLineFlagConstraintList.hpp"
63 #include "runtime/commandLineFlagWriteableList.hpp"
64 #include "runtime/commandLineFlagRangeList.hpp"
65 #include "runtime/deoptimization.hpp"
66 #include "runtime/frame.inline.hpp"
67 #include "runtime/globals.hpp"
68 #include "runtime/init.hpp"
69 #include "runtime/interfaceSupport.hpp"
70 #include "runtime/java.hpp"
71 #include "runtime/javaCalls.hpp"
72 #include "runtime/jniPeriodicChecker.hpp"
73 #include "runtime/timerTrace.hpp"
74 #include "runtime/memprofiler.hpp"
75 #include "runtime/mutexLocker.hpp"
76 #include "runtime/objectMonitor.hpp"
77 #include "runtime/orderAccess.inline.hpp"
78 #include "runtime/osThread.hpp"
79 #include "runtime/safepoint.hpp"
80 #include "runtime/sharedRuntime.hpp"
81 #include "runtime/statSampler.hpp"
82 #include "runtime/stubRoutines.hpp"
83 #include "runtime/sweeper.hpp"
84 #include "runtime/task.hpp"
85 #include "runtime/thread.inline.hpp"
86 #include "runtime/threadCritical.hpp"
87 #include "runtime/vframe.hpp"
88 #include "runtime/vframeArray.hpp"
89 #include "runtime/vframe_hp.hpp"
90 #include "runtime/vmThread.hpp"
91 #include "runtime/vm_operations.hpp"
92 #include "runtime/vm_version.hpp"
93 #include "services/attachListener.hpp"
94 #include "services/management.hpp"
95 #include "services/memTracker.hpp"
96 #include "services/threadService.hpp"
97 #include "trace/traceMacros.hpp"
98 #include "trace/tracing.hpp"
99 #include "utilities/align.hpp"
100 #include "utilities/defaultStream.hpp"
101 #include "utilities/dtrace.hpp"
102 #include "utilities/events.hpp"
103 #include "utilities/macros.hpp"
104 #include "utilities/preserveException.hpp"
105 #include "utilities/vmError.hpp"
106 #if INCLUDE_ALL_GCS
107 #include "gc/cms/concurrentMarkSweepThread.hpp"
108 #include "gc/g1/concurrentMarkThread.inline.hpp"
109 #include "gc/parallel/pcTasks.hpp"
110 #endif // INCLUDE_ALL_GCS
111 #if INCLUDE_JVMCI
112 #include "jvmci/jvmciCompiler.hpp"
113 #include "jvmci/jvmciRuntime.hpp"
114 #include "logging/logHandle.hpp"
115 #endif
116 #ifdef COMPILER1
117 #include "c1/c1_Compiler.hpp"
118 #endif
119 #ifdef COMPILER2
120 #include "opto/c2compiler.hpp"
121 #include "opto/idealGraphPrinter.hpp"
122 #endif
123 #if INCLUDE_RTM_OPT
124 #include "runtime/rtmLocking.hpp"
176 AllocFailStrategy::RETURN_NULL);
177 void* aligned_addr = align_up(real_malloc_addr, alignment);
178 assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
179 ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
180 "JavaThread alignment code overflowed allocated storage");
181 if (aligned_addr != real_malloc_addr) {
182 log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
183 p2i(real_malloc_addr),
184 p2i(aligned_addr));
185 }
186 ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
187 return aligned_addr;
188 } else {
189 return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
190 : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
191 }
192 }
193
194 void Thread::operator delete(void* p) {
195 if (UseBiasedLocking) {
196 void* real_malloc_addr = ((Thread*) p)->_real_malloc_address;
197 FreeHeap(real_malloc_addr);
198 } else {
199 FreeHeap(p);
200 }
201 }
202
203
204 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
205 // JavaThread
206
207
208 Thread::Thread() {
209 // stack and get_thread
210 set_stack_base(NULL);
211 set_stack_size(0);
212 set_self_raw_id(0);
213 set_lgrp_id(-1);
214 DEBUG_ONLY(clear_suspendible_thread();)
215
216 // allocated data structures
217 set_osthread(NULL);
218 set_resource_area(new (mtThread)ResourceArea());
219 DEBUG_ONLY(_current_resource_mark = NULL;)
220 set_handle_area(new (mtThread) HandleArea(NULL));
221 set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
222 set_active_handles(NULL);
223 set_free_handle_block(NULL);
224 set_last_handle_mark(NULL);
225
226 // This initial value ==> never claimed.
227 _oops_do_parity = 0;
228
229 // the handle mark links itself to last_handle_mark
230 new HandleMark(this);
231
232 // plain initialization
233 debug_only(_owned_locks = NULL;)
234 debug_only(_allow_allocation_count = 0;)
235 NOT_PRODUCT(_allow_safepoint_count = 0;)
236 NOT_PRODUCT(_skip_gcalot = false;)
237 _jvmti_env_iteration_count = 0;
238 set_allocated_bytes(0);
239 _vm_operation_started_count = 0;
240 _vm_operation_completed_count = 0;
241 _current_pending_monitor = NULL;
242 _current_pending_monitor_is_from_java = true;
243 _current_waiting_monitor = NULL;
244 _num_nested_signal = 0;
245 omFreeList = NULL;
246 omFreeCount = 0;
247 omFreeProvision = 32;
379 _SR_lock = NULL;
380
381 // osthread() can be NULL, if creation of thread failed.
382 if (osthread() != NULL) os::free_thread(osthread());
383
384 // clear Thread::current if thread is deleting itself.
385 // Needed to ensure JNI correctly detects non-attached threads.
386 if (this == Thread::current()) {
387 clear_thread_current();
388 }
389
390 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
391 }
392
393 // NOTE: dummy function for assertion purpose.
394 void Thread::run() {
395 ShouldNotReachHere();
396 }
397
398 #ifdef ASSERT
399 // Private method to check for dangling thread pointer
400 void check_for_dangling_thread_pointer(Thread *thread) {
401 assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
402 "possibility of dangling Thread pointer");
403 }
404 #endif
405
406 ThreadPriority Thread::get_priority(const Thread* const thread) {
407 ThreadPriority priority;
408 // Can return an error!
409 (void)os::get_priority(thread, priority);
410 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
411 return priority;
412 }
413
414 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
415 debug_only(check_for_dangling_thread_pointer(thread);)
416 // Can return an error!
417 (void)os::set_priority(thread, priority);
418 }
419
420
421 void Thread::start(Thread* thread) {
713
714 if (!pending) {
715 // A cancelled suspend request is the only false return from
716 // is_ext_suspend_completed() that keeps us from staying in the
717 // retry loop.
718 *bits |= 0x00080000;
719 return false;
720 }
721
722 if (is_suspended) {
723 *bits |= 0x00100000;
724 return true;
725 }
726 } // end retry loop
727
728 // thread did not suspend after all our retries
729 *bits |= 0x00200000;
730 return false;
731 }
732
733 #ifndef PRODUCT
734 void JavaThread::record_jump(address target, address instr, const char* file,
735 int line) {
736
737 // This should not need to be atomic as the only way for simultaneous
738 // updates is via interrupts. Even then this should be rare or non-existent
739 // and we don't care that much anyway.
740
741 int index = _jmp_ring_index;
742 _jmp_ring_index = (index + 1) & (jump_ring_buffer_size - 1);
743 _jmp_ring[index]._target = (intptr_t) target;
744 _jmp_ring[index]._instruction = (intptr_t) instr;
745 _jmp_ring[index]._file = file;
746 _jmp_ring[index]._line = line;
747 }
748 #endif // PRODUCT
749
750 void Thread::interrupt(Thread* thread) {
751 debug_only(check_for_dangling_thread_pointer(thread);)
752 os::interrupt(thread);
791 void Thread::metadata_handles_do(void f(Metadata*)) {
792 // Only walk the Handles in Thread.
793 if (metadata_handles() != NULL) {
794 for (int i = 0; i< metadata_handles()->length(); i++) {
795 f(metadata_handles()->at(i));
796 }
797 }
798 }
799
800 void Thread::print_on(outputStream* st) const {
801 // get_priority assumes osthread initialized
802 if (osthread() != NULL) {
803 int os_prio;
804 if (os::get_native_priority(this, &os_prio) == OS_OK) {
805 st->print("os_prio=%d ", os_prio);
806 }
807 st->print("tid=" INTPTR_FORMAT " ", p2i(this));
808 ext().print_on(st);
809 osthread()->print_on(st);
810 }
811 debug_only(if (WizardMode) print_owned_locks_on(st);)
812 }
813
814 // Thread::print_on_error() is called by fatal error handler. Don't use
815 // any lock or allocate memory.
816 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
817 assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates");
818
819 if (is_VM_thread()) { st->print("VMThread"); }
820 else if (is_GC_task_thread()) { st->print("GCTaskThread"); }
821 else if (is_Watcher_thread()) { st->print("WatcherThread"); }
822 else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); }
823 else { st->print("Thread"); }
824
825 if (is_Named_thread()) {
826 st->print(" \"%s\"", name());
827 }
828
829 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
830 p2i(stack_end()), p2i(stack_base()));
831
832 if (osthread()) {
833 st->print(" [id=%d]", osthread()->thread_id());
834 }
835 }
836
837 void Thread::print_value_on(outputStream* st) const {
838 if (is_Named_thread()) {
839 st->print(" \"%s\" ", name());
840 }
841 st->print(INTPTR_FORMAT, p2i(this)); // print address
842 }
843
844 #ifdef ASSERT
845 void Thread::print_owned_locks_on(outputStream* st) const {
846 Monitor *cur = _owned_locks;
847 if (cur == NULL) {
848 st->print(" (no locks) ");
849 } else {
850 st->print_cr(" Locks owned:");
851 while (cur) {
852 cur->print_on(st);
853 cur = cur->next();
854 }
855 }
856 }
857
858 static int ref_use_count = 0;
859
860 bool Thread::owns_locks_but_compiled_lock() const {
861 for (Monitor *cur = _owned_locks; cur; cur = cur->next()) {
862 if (cur != Compile_lock) return true;
863 }
864 return false;
865 }
866
867
868 #endif
869
870 #ifndef PRODUCT
871
872 // The flag: potential_vm_operation notifies if this particular safepoint state could potential
873 // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that
874 // no threads which allow_vm_block's are held
875 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
876 // Check if current thread is allowed to block at a safepoint
877 if (!(_allow_safepoint_count == 0)) {
878 fatal("Possible safepoint reached by thread that does not allow it");
879 }
880 if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
881 fatal("LEAF method calling lock?");
882 }
883
884 #ifdef ASSERT
885 if (potential_vm_operation && is_Java_thread()
886 && !Universe::is_bootstrapping()) {
887 // Make sure we do not hold any locks that the VM thread also uses.
888 // This could potentially lead to deadlocks
889 for (Monitor *cur = _owned_locks; cur; cur = cur->next()) {
890 // Threads_lock is special, since the safepoint synchronization will not start before this is
891 // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock,
892 // since it is used to transfer control between JavaThreads and the VMThread
893 // Do not *exclude* any locks unless you are absolutely sure it is correct. Ask someone else first!
1379
1380 void WatcherThread::print_on(outputStream* st) const {
1381 st->print("\"%s\" ", name());
1382 Thread::print_on(st);
1383 st->cr();
1384 }
1385
1386 // ======= JavaThread ========
1387
1388 #if INCLUDE_JVMCI
1389
1390 jlong* JavaThread::_jvmci_old_thread_counters;
1391
1392 bool jvmci_counters_include(JavaThread* thread) {
1393 oop threadObj = thread->threadObj();
1394 return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
1395 }
1396
1397 void JavaThread::collect_counters(typeArrayOop array) {
1398 if (JVMCICounterSize > 0) {
1399 MutexLocker tl(Threads_lock);
1400 for (int i = 0; i < array->length(); i++) {
1401 array->long_at_put(i, _jvmci_old_thread_counters[i]);
1402 }
1403 for (JavaThread* tp = Threads::first(); tp != NULL; tp = tp->next()) {
1404 if (jvmci_counters_include(tp)) {
1405 for (int i = 0; i < array->length(); i++) {
1406 array->long_at_put(i, array->long_at(i) + tp->_jvmci_counters[i]);
1407 }
1408 }
1409 }
1410 }
1411 }
1412
1413 #endif // INCLUDE_JVMCI
1414
1415 // A JavaThread is a normal Java thread
1416
1417 void JavaThread::initialize() {
1418 // Initialize fields
1419
1420 set_saved_exception_pc(NULL);
1421 set_threadObj(NULL);
1422 _anchor.clear();
1423 set_entry_point(NULL);
1424 set_jni_functions(jni_functions());
1425 set_callee_target(NULL);
1426 set_vm_result(NULL);
1427 set_vm_result_2(NULL);
1428 set_vframe_array_head(NULL);
1429 set_vframe_array_last(NULL);
1430 set_deferred_locals(NULL);
1431 set_deopt_mark(NULL);
1432 set_deopt_compiled_method(NULL);
1433 clear_must_deopt_id();
1434 set_monitor_chunks(NULL);
1435 set_next(NULL);
1436 set_thread_state(_thread_new);
1437 _terminated = _not_terminated;
1438 _privileged_stack_top = NULL;
1439 _array_for_gc = NULL;
1440 _suspend_equivalent = false;
1441 _in_deopt_handler = 0;
1442 _doing_unsafe_access = false;
1443 _stack_guard_state = stack_guard_unused;
1444 #if INCLUDE_JVMCI
1445 _pending_monitorenter = false;
1446 _pending_deoptimization = -1;
1447 _pending_failed_speculation = NULL;
1448 _pending_transfer_to_interpreter = false;
1449 _adjusting_comp_level = false;
1450 _jvmci._alternate_call_target = NULL;
1451 assert(_jvmci._implicit_exception_pc == NULL, "must be");
1452 if (JVMCICounterSize > 0) {
1453 _jvmci_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal);
1454 memset(_jvmci_counters, 0, sizeof(jlong) * JVMCICounterSize);
1455 } else {
1692 void JavaThread::thread_main_inner() {
1693 assert(JavaThread::current() == this, "sanity check");
1694 assert(this->threadObj() != NULL, "just checking");
1695
1696 // Execute thread entry point unless this thread has a pending exception
1697 // or has been stopped before starting.
1698 // Note: Due to JVM_StopThread we can have pending exceptions already!
1699 if (!this->has_pending_exception() &&
1700 !java_lang_Thread::is_stillborn(this->threadObj())) {
1701 {
1702 ResourceMark rm(this);
1703 this->set_native_thread_name(this->get_thread_name());
1704 }
1705 HandleMark hm(this);
1706 this->entry_point()(this, this);
1707 }
1708
1709 DTRACE_THREAD_PROBE(stop, this);
1710
1711 this->exit(false);
1712 delete this;
1713 }
1714
1715
1716 static void ensure_join(JavaThread* thread) {
1717 // We do not need to grap the Threads_lock, since we are operating on ourself.
1718 Handle threadObj(thread, thread->threadObj());
1719 assert(threadObj.not_null(), "java thread object must exist");
1720 ObjectLocker lock(threadObj, thread);
1721 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1722 thread->clear_pending_exception();
1723 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
1724 java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1725 // Clear the native thread instance - this makes isAlive return false and allows the join()
1726 // to complete once we've done the notify_all below
1727 java_lang_Thread::set_thread(threadObj(), NULL);
1728 lock.notify_all(thread);
1729 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1730 thread->clear_pending_exception();
1731 }
1732
1733
1734 // For any new cleanup additions, please check to see if they need to be applied to
1735 // cleanup_failed_attach_current_thread as well.
1736 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
1737 assert(this == JavaThread::current(), "thread consistency check");
1738
1739 HandleMark hm(this);
1740 Handle uncaught_exception(this, this->pending_exception());
1741 this->clear_pending_exception();
1742 Handle threadObj(this, this->threadObj());
1743 assert(threadObj.not_null(), "Java thread object should be created");
1744
1745 // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place
1746 {
1747 EXCEPTION_MARK;
1748
1749 CLEAR_PENDING_EXCEPTION;
1750 }
1751 if (!destroy_vm) {
1752 if (uncaught_exception.not_null()) {
1753 EXCEPTION_MARK;
1754 // Call method Thread.dispatchUncaughtException().
1755 Klass* thread_klass = SystemDictionary::Thread_klass();
1756 JavaValue result(T_VOID);
1757 JavaCalls::call_virtual(&result,
1758 threadObj, thread_klass,
1818 // Implied else:
1819 // Things get a little tricky here. We have a pending external
1820 // suspend request, but we are holding the SR_lock so we
1821 // can't just self-suspend. So we temporarily drop the lock
1822 // and then self-suspend.
1823 }
1824
1825 ThreadBlockInVM tbivm(this);
1826 java_suspend_self();
1827
1828 // We're done with this suspend request, but we have to loop around
1829 // and check again. Eventually we will get SR_lock without a pending
1830 // external suspend request and will be able to mark ourselves as
1831 // exiting.
1832 }
1833 // no more external suspends are allowed at this point
1834 } else {
1835 // before_exit() has already posted JVMTI THREAD_END events
1836 }
1837
1838 // Notify waiters on thread object. This has to be done after exit() is called
1839 // on the thread (if the thread is the last thread in a daemon ThreadGroup the
1840 // group should have the destroyed bit set before waiters are notified).
1841 ensure_join(this);
1842 assert(!this->has_pending_exception(), "ensure_join should have cleared");
1843
1844 // 6282335 JNI DetachCurrentThread spec states that all Java monitors
1845 // held by this thread must be released. The spec does not distinguish
1846 // between JNI-acquired and regular Java monitors. We can only see
1847 // regular Java monitors here if monitor enter-exit matching is broken.
1848 //
1849 // Optionally release any monitors for regular JavaThread exits. This
1850 // is provided as a work around for any bugs in monitor enter-exit
1851 // matching. This can be expensive so it is not enabled by default.
1852 //
1853 // ensure_join() ignores IllegalThreadStateExceptions, and so does
1854 // ObjectSynchronizer::release_monitors_owned_by_thread().
1855 if (exit_type == jni_detach || ObjectMonitor::Knob_ExitRelease) {
1856 // Sanity check even though JNI DetachCurrentThread() would have
1857 // returned JNI_ERR if there was a Java frame. JavaThread exit
1858 // should be done executing Java code by the time we get here.
1859 assert(!this->has_last_Java_frame(),
1860 "should not have a Java frame when detaching or exiting");
1861 ObjectSynchronizer::release_monitors_owned_by_thread(this);
1862 assert(!this->has_pending_exception(), "release_monitors should have cleared");
1863 }
1891
1892 // We must flush any deferred card marks before removing a thread from
1893 // the list of active threads.
1894 Universe::heap()->flush_deferred_store_barrier(this);
1895 assert(deferred_card_mark().is_empty(), "Should have been flushed");
1896
1897 #if INCLUDE_ALL_GCS
1898 // We must flush the G1-related buffers before removing a thread
1899 // from the list of active threads. We must do this after any deferred
1900 // card marks have been flushed (above) so that any entries that are
1901 // added to the thread's dirty card queue as a result are not lost.
1902 if (UseG1GC) {
1903 flush_barrier_queues();
1904 }
1905 #endif // INCLUDE_ALL_GCS
1906
1907 log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").",
1908 exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
1909 os::current_thread_id());
1910
1911 // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
1912 Threads::remove(this);
1913 }
1914
1915 #if INCLUDE_ALL_GCS
1916 // Flush G1-related queues.
1917 void JavaThread::flush_barrier_queues() {
1918 satb_mark_queue().flush();
1919 dirty_card_queue().flush();
1920 }
1921
1922 void JavaThread::initialize_queues() {
1923 assert(!SafepointSynchronize::is_at_safepoint(),
1924 "we should not be at a safepoint");
1925
1926 SATBMarkQueue& satb_queue = satb_mark_queue();
1927 SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set();
1928 // The SATB queue should have been constructed with its active
1929 // field set to false.
1930 assert(!satb_queue.is_active(), "SATB queue should not be active");
1931 assert(satb_queue.is_empty(), "SATB queue should be empty");
1932 // If we are creating the thread during a marking cycle, we should
1952 if (free_handle_block() != NULL) {
1953 JNIHandleBlock* block = free_handle_block();
1954 set_free_handle_block(NULL);
1955 JNIHandleBlock::release_block(block);
1956 }
1957
1958 // These have to be removed while this is still a valid thread.
1959 remove_stack_guard_pages();
1960
1961 if (UseTLAB) {
1962 tlab().make_parsable(true); // retire TLAB, if any
1963 }
1964
1965 #if INCLUDE_ALL_GCS
1966 if (UseG1GC) {
1967 flush_barrier_queues();
1968 }
1969 #endif // INCLUDE_ALL_GCS
1970
1971 Threads::remove(this);
1972 delete this;
1973 }
1974
1975
1976
1977
1978 JavaThread* JavaThread::active() {
1979 Thread* thread = Thread::current();
1980 if (thread->is_Java_thread()) {
1981 return (JavaThread*) thread;
1982 } else {
1983 assert(thread->is_VM_thread(), "this must be a vm thread");
1984 VM_Operation* op = ((VMThread*) thread)->vm_operation();
1985 JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
1986 assert(ret->is_Java_thread(), "must be a Java thread");
1987 return ret;
1988 }
1989 }
1990
1991 bool JavaThread::is_lock_owned(address adr) const {
1992 if (Thread::is_lock_owned(adr)) return true;
2207 }
2208
2209
2210 // Interrupt thread so it will wake up from a potential wait()
2211 Thread::interrupt(this);
2212 }
2213
2214 // External suspension mechanism.
2215 //
2216 // Tell the VM to suspend a thread when ever it knows that it does not hold on
2217 // to any VM_locks and it is at a transition
2218 // Self-suspension will happen on the transition out of the vm.
2219 // Catch "this" coming in from JNIEnv pointers when the thread has been freed
2220 //
2221 // Guarantees on return:
2222 // + Target thread will not execute any new bytecode (that's why we need to
2223 // force a safepoint)
2224 // + Target thread will not enter any new monitors
2225 //
2226 void JavaThread::java_suspend() {
2227 { MutexLocker mu(Threads_lock);
2228 if (!Threads::includes(this) || is_exiting() || this->threadObj() == NULL) {
2229 return;
2230 }
2231 }
2232
2233 { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2234 if (!is_external_suspend()) {
2235 // a racing resume has cancelled us; bail out now
2236 return;
2237 }
2238
2239 // suspend is done
2240 uint32_t debug_bits = 0;
2241 // Warning: is_ext_suspend_completed() may temporarily drop the
2242 // SR_lock to allow the thread to reach a stable thread state if
2243 // it is currently in a transient thread state.
2244 if (is_ext_suspend_completed(false /* !called_by_wait */,
2245 SuspendRetryDelay, &debug_bits)) {
2246 return;
2247 }
2248 }
2249
2250 VM_ThreadSuspend vm_suspend;
2251 VMThread::execute(&vm_suspend);
2299 // it. This would be a "bad thing (TM)" and cause the stack walker
2300 // to crash. We stay self-suspended until there are no more pending
2301 // external suspend requests.
2302 while (is_external_suspend()) {
2303 ret++;
2304 this->set_ext_suspended();
2305
2306 // _ext_suspended flag is cleared by java_resume()
2307 while (is_ext_suspended()) {
2308 this->SR_lock()->wait(Mutex::_no_safepoint_check_flag);
2309 }
2310 }
2311
2312 return ret;
2313 }
2314
2315 #ifdef ASSERT
2316 // verify the JavaThread has not yet been published in the Threads::list, and
2317 // hence doesn't need protection from concurrent access at this stage
2318 void JavaThread::verify_not_published() {
2319 if (!Threads_lock->owned_by_self()) {
2320 MutexLockerEx ml(Threads_lock, Mutex::_no_safepoint_check_flag);
2321 assert(!Threads::includes(this),
2322 "java thread shouldn't have been published yet!");
2323 } else {
2324 assert(!Threads::includes(this),
2325 "java thread shouldn't have been published yet!");
2326 }
2327 }
2328 #endif
2329
2330 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2331 // progress or when _suspend_flags is non-zero.
2332 // Current thread needs to self-suspend if there is a suspend request and/or
2333 // block if a safepoint is in progress.
2334 // Async exception ISN'T checked.
2335 // Note only the ThreadInVMfromNative transition can call this function
2336 // directly and when thread state is _thread_in_native_trans
2337 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
2338 assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
2339
2340 JavaThread *curJT = JavaThread::current();
2341 bool do_self_suspend = thread->is_external_suspend();
2342
2343 assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
2344
2345 // If JNIEnv proxies are allowed, don't self-suspend if the target
2346 // thread is not the current thread. In older versions of jdbx, jdbx
2427 check_special_condition_for_native_trans(thread);
2428
2429 // Finish the transition
2430 thread->set_thread_state(_thread_in_Java);
2431
2432 if (thread->do_critical_native_unlock()) {
2433 ThreadInVMfromJavaNoAsyncException tiv(thread);
2434 GCLocker::unlock_critical(thread);
2435 thread->clear_critical_native_unlock();
2436 }
2437 }
2438
2439 // We need to guarantee the Threads_lock here, since resumes are not
2440 // allowed during safepoint synchronization
2441 // Can only resume from an external suspension
2442 void JavaThread::java_resume() {
2443 assert_locked_or_safepoint(Threads_lock);
2444
2445 // Sanity check: thread is gone, has started exiting or the thread
2446 // was not externally suspended.
2447 if (!Threads::includes(this) || is_exiting() || !is_external_suspend()) {
2448 return;
2449 }
2450
2451 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2452
2453 clear_external_suspend();
2454
2455 if (is_ext_suspended()) {
2456 clear_ext_suspended();
2457 SR_lock()->notify_all();
2458 }
2459 }
2460
2461 size_t JavaThread::_stack_red_zone_size = 0;
2462 size_t JavaThread::_stack_yellow_zone_size = 0;
2463 size_t JavaThread::_stack_reserved_zone_size = 0;
2464 size_t JavaThread::_stack_shadow_zone_size = 0;
2465
2466 void JavaThread::create_stack_guard_pages() {
2467 if (!os::uses_stack_guard_pages() || _stack_guard_state != stack_guard_unused) { return; }
2895 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
2896 st->print("%s", get_thread_name_string(buf, buflen));
2897 }
2898
2899 // Called by fatal error handler. The difference between this and
2900 // JavaThread::print() is that we can't grab lock or allocate memory.
2901 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
2902 st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
2903 oop thread_obj = threadObj();
2904 if (thread_obj != NULL) {
2905 if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
2906 }
2907 st->print(" [");
2908 st->print("%s", _get_thread_state_name(_thread_state));
2909 if (osthread()) {
2910 st->print(", id=%d", osthread()->thread_id());
2911 }
2912 st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
2913 p2i(stack_end()), p2i(stack_base()));
2914 st->print("]");
2915 return;
2916 }
2917
2918 // Verification
2919
2920 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
2921
2922 void JavaThread::verify() {
2923 // Verify oops in the thread.
2924 oops_do(&VerifyOopClosure::verify_oop, NULL);
2925
2926 // Verify the stack frames.
2927 frames_do(frame_verify);
2928 }
2929
2930 // CR 6300358 (sub-CR 2137150)
2931 // Most callers of this method assume that it can't return NULL but a
2932 // thread may not have a name whilst it is in the process of attaching to
2933 // the VM - see CR 6412693, and there are places where a JavaThread can be
2934 // seen prior to having it's threadObj set (eg JNI attaching threads and
3299 // a scan.
3300 cf->do_code_blob(_scanned_compiled_method);
3301 }
3302 }
3303
3304
3305 // ======= Threads ========
3306
3307 // The Threads class links together all active threads, and provides
3308 // operations over all threads. It is protected by its own Mutex
3309 // lock, which is also used in other contexts to protect thread
3310 // operations from having the thread being operated on from exiting
3311 // and going away unexpectedly (e.g., safepoint synchronization)
3312
3313 JavaThread* Threads::_thread_list = NULL;
3314 int Threads::_number_of_threads = 0;
3315 int Threads::_number_of_non_daemon_threads = 0;
3316 int Threads::_return_code = 0;
3317 int Threads::_thread_claim_parity = 0;
3318 size_t JavaThread::_stack_size_at_create = 0;
3319 #ifdef ASSERT
3320 bool Threads::_vm_complete = false;
3321 #endif
3322
3323 // All JavaThreads
3324 #define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next())
3325
3326 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
3327 void Threads::threads_do(ThreadClosure* tc) {
3328 assert_locked_or_safepoint(Threads_lock);
3329 // ALL_JAVA_THREADS iterates through all JavaThreads
3330 ALL_JAVA_THREADS(p) {
3331 tc->do_thread(p);
3332 }
3333 // Someday we could have a table or list of all non-JavaThreads.
3334 // For now, just manually iterate through them.
3335 tc->do_thread(VMThread::vm_thread());
3336 Universe::heap()->gc_threads_do(tc);
3337 WatcherThread *wt = WatcherThread::watcher_thread();
3338 // Strictly speaking, the following NULL check isn't sufficient to make sure
3339 // the data for WatcherThread is still valid upon being examined. However,
3340 // considering that WatchThread terminates when the VM is on the way to
3341 // exit at safepoint, the chance of the above is extremely small. The right
3342 // way to prevent termination of WatcherThread would be to acquire
3343 // Terminator_lock, but we can't do that without violating the lock rank
3344 // checking in some cases.
3405 if (result.get_jint() != JNI_OK) {
3406 vm_exit_during_initialization(); // no message or exception
3407 }
3408
3409 universe_post_module_init();
3410 }
3411
3412 // Phase 3. final setup - set security manager, system class loader and TCCL
3413 //
3414 // This will instantiate and set the security manager, set the system class
3415 // loader as well as the thread context class loader. The security manager
3416 // and system class loader may be a custom class loaded from -Xbootclasspath/a,
3417 // other modules or the application's classpath.
3418 static void call_initPhase3(TRAPS) {
3419 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3420 JavaValue result(T_VOID);
3421 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
3422 vmSymbols::void_method_signature(), CHECK);
3423 }
3424
3425 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
3426 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
3427
3428 if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
3429 create_vm_init_libraries();
3430 }
3431
3432 initialize_class(vmSymbols::java_lang_String(), CHECK);
3433
3434 // Inject CompactStrings value after the static initializers for String ran.
3435 java_lang_String::set_compact_strings(CompactStrings);
3436
3437 // Initialize java_lang.System (needed before creating the thread)
3438 initialize_class(vmSymbols::java_lang_System(), CHECK);
3439 // The VM creates & returns objects of this class. Make sure it's initialized.
3440 initialize_class(vmSymbols::java_lang_Class(), CHECK);
3441 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
3442 Handle thread_group = create_initial_thread_group(CHECK);
3443 Universe::set_main_thread_group(thread_group());
3444 initialize_class(vmSymbols::java_lang_Thread(), CHECK);
3583 #if INCLUDE_JVMCI
3584 if (JVMCICounterSize > 0) {
3585 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal);
3586 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
3587 } else {
3588 JavaThread::_jvmci_old_thread_counters = NULL;
3589 }
3590 #endif // INCLUDE_JVMCI
3591
3592 // Attach the main thread to this os thread
3593 JavaThread* main_thread = new JavaThread();
3594 main_thread->set_thread_state(_thread_in_vm);
3595 main_thread->initialize_thread_current();
3596 // must do this before set_active_handles
3597 main_thread->record_stack_base_and_size();
3598 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
3599
3600 if (!main_thread->set_as_starting_thread()) {
3601 vm_shutdown_during_initialization(
3602 "Failed necessary internal allocation. Out of swap space");
3603 delete main_thread;
3604 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3605 return JNI_ENOMEM;
3606 }
3607
3608 // Enable guard page *after* os::create_main_thread(), otherwise it would
3609 // crash Linux VM, see notes in os_linux.cpp.
3610 main_thread->create_stack_guard_pages();
3611
3612 // Initialize Java-Level synchronization subsystem
3613 ObjectMonitor::Initialize();
3614
3615 // Initialize global modules
3616 jint status = init_globals();
3617 if (status != JNI_OK) {
3618 delete main_thread;
3619 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3620 return status;
3621 }
3622
3623 if (TRACE_INITIALIZE() != JNI_OK) {
3624 vm_exit_during_initialization("Failed to initialize tracing backend");
3625 }
3626
3627 // Should be done after the heap is fully created
3628 main_thread->cache_global_variables();
3629
3630 HandleMark hm;
3631
3632 { MutexLocker mu(Threads_lock);
3633 Threads::add(main_thread);
3634 }
3635
3636 // Any JVMTI raw monitors entered in onload will transition into
3637 // real raw monitor. VM is setup enough here for raw monitor enter.
3638 JvmtiExport::transition_pending_onload_raw_monitors();
4004 AgentLibrary* agent;
4005
4006 for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
4007 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
4008
4009 if (on_load_entry != NULL) {
4010 // Invoke the JVM_OnLoad function
4011 JavaThread* thread = JavaThread::current();
4012 ThreadToNativeFromVM ttn(thread);
4013 HandleMark hm(thread);
4014 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
4015 if (err != JNI_OK) {
4016 vm_exit_during_initialization("-Xrun library failed to init", agent->name());
4017 }
4018 } else {
4019 vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
4020 }
4021 }
4022 }
4023
4024 JavaThread* Threads::find_java_thread_from_java_tid(jlong java_tid) {
4025 assert(Threads_lock->owned_by_self(), "Must hold Threads_lock");
4026
4027 JavaThread* java_thread = NULL;
4028 // Sequential search for now. Need to do better optimization later.
4029 for (JavaThread* thread = Threads::first(); thread != NULL; thread = thread->next()) {
4030 oop tobj = thread->threadObj();
4031 if (!thread->is_exiting() &&
4032 tobj != NULL &&
4033 java_tid == java_lang_Thread::thread_id(tobj)) {
4034 java_thread = thread;
4035 break;
4036 }
4037 }
4038 return java_thread;
4039 }
4040
4041
4042 // Last thread running calls java.lang.Shutdown.shutdown()
4043 void JavaThread::invoke_shutdown_hooks() {
4044 HandleMark hm(this);
4045
4046 // We could get here with a pending exception, if so clear it now.
4047 if (this->has_pending_exception()) {
4048 this->clear_pending_exception();
4049 }
4050
4051 EXCEPTION_MARK;
4052 Klass* shutdown_klass =
4053 SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
4054 THREAD);
4055 if (shutdown_klass != NULL) {
4056 // SystemDictionary::resolve_or_null will return null if there was
4057 // an exception. If we cannot load the Shutdown class, just don't
4058 // call Shutdown.shutdown() at all. This will mean the shutdown hooks
4059 // and finalizers (if runFinalizersOnExit is set) won't be run.
4060 // Note that if a shutdown hook was registered or runFinalizersOnExit
4061 // was called, the Shutdown class would have already been loaded
4146 VMThread::wait_for_vm_thread_exit();
4147 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
4148 VMThread::destroy();
4149 }
4150
4151 // clean up ideal graph printers
4152 #if defined(COMPILER2) && !defined(PRODUCT)
4153 IdealGraphPrinter::clean_up();
4154 #endif
4155
4156 // Now, all Java threads are gone except daemon threads. Daemon threads
4157 // running Java code or in VM are stopped by the Safepoint. However,
4158 // daemon threads executing native code are still running. But they
4159 // will be stopped at native=>Java/VM barriers. Note that we can't
4160 // simply kill or suspend them, as it is inherently deadlock-prone.
4161
4162 VM_Exit::set_vm_exited();
4163
4164 notify_vm_shutdown();
4165
4166 delete thread;
4167
4168 #if INCLUDE_JVMCI
4169 if (JVMCICounterSize > 0) {
4170 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
4171 }
4172 #endif
4173
4174 // exit_globals() will delete tty
4175 exit_globals();
4176
4177 LogConfiguration::finalize();
4178
4179 return true;
4180 }
4181
4182
4183 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
4184 if (version == JNI_VERSION_1_1) return JNI_TRUE;
4185 return is_supported_jni_version(version);
4186 }
4187
4188
4189 jboolean Threads::is_supported_jni_version(jint version) {
4190 if (version == JNI_VERSION_1_2) return JNI_TRUE;
4191 if (version == JNI_VERSION_1_4) return JNI_TRUE;
4192 if (version == JNI_VERSION_1_6) return JNI_TRUE;
4193 if (version == JNI_VERSION_1_8) return JNI_TRUE;
4194 if (version == JNI_VERSION_9) return JNI_TRUE;
4195 if (version == JNI_VERSION_10) return JNI_TRUE;
4196 return JNI_FALSE;
4197 }
4198
4199
4200 void Threads::add(JavaThread* p, bool force_daemon) {
4201 // The threads lock must be owned at this point
4202 assert_locked_or_safepoint(Threads_lock);
4203
4204 // See the comment for this method in thread.hpp for its purpose and
4205 // why it is called here.
4206 p->initialize_queues();
4207 p->set_next(_thread_list);
4208 _thread_list = p;
4209 _number_of_threads++;
4210 oop threadObj = p->threadObj();
4211 bool daemon = true;
4212 // Bootstrapping problem: threadObj can be null for initial
4213 // JavaThread (or for threads attached via JNI)
4214 if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) {
4215 _number_of_non_daemon_threads++;
4216 daemon = false;
4217 }
4218
4219 ThreadService::add_thread(p, daemon);
4220
4221 // Possible GC point.
4222 Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p));
4223 }
4224
4225 void Threads::remove(JavaThread* p) {
4226
4227 // Reclaim the objectmonitors from the omInUseList and omFreeList of the moribund thread.
4228 ObjectSynchronizer::omFlush(p);
4229
4230 // Extra scope needed for Thread_lock, so we can check
4231 // that we do not remove thread without safepoint code notice
4232 { MutexLocker ml(Threads_lock);
4233
4234 assert(includes(p), "p must be present");
4235
4236 JavaThread* current = _thread_list;
4237 JavaThread* prev = NULL;
4238
4239 while (current != p) {
4240 prev = current;
4241 current = current->next();
4242 }
4243
4244 if (prev) {
4245 prev->set_next(current->next());
4246 } else {
4247 _thread_list = p->next();
4248 }
4249 _number_of_threads--;
4250 oop threadObj = p->threadObj();
4251 bool daemon = true;
4252 if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
4253 _number_of_non_daemon_threads--;
4254 daemon = false;
4255
4256 // Only one thread left, do a notify on the Threads_lock so a thread waiting
4257 // on destroy_vm will wake up.
4258 if (number_of_non_daemon_threads() == 1) {
4259 Threads_lock->notify_all();
4260 }
4261 }
4262 ThreadService::remove_thread(p, daemon);
4263
4264 // Make sure that safepoint code disregard this thread. This is needed since
4265 // the thread might mess around with locks after this point. This can cause it
4266 // to do callbacks into the safepoint code. However, the safepoint code is not aware
4267 // of this thread since it is removed from the queue.
4268 p->set_terminated_value();
4269 } // unlock Threads_lock
4270
4271 // Since Events::log uses a lock, we grab it outside the Threads_lock
4272 Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p));
4273 }
4274
4275 // Threads_lock must be held when this is called (or must be called during a safepoint)
4276 bool Threads::includes(JavaThread* p) {
4277 assert(Threads_lock->is_locked(), "sanity check");
4278 ALL_JAVA_THREADS(q) {
4279 if (q == p) {
4280 return true;
4281 }
4282 }
4283 return false;
4284 }
4285
4286 // Operations on the Threads list for GC. These are not explicitly locked,
4287 // but the garbage collector must provide a safe context for them to run.
4288 // In particular, these things should never be called when the Threads_lock
4289 // is held by some other thread. (Note: the Safepoint abstraction also
4290 // uses the Threads_lock to guarantee this property. It also makes sure that
4291 // all threads gets blocked when exiting or starting).
4292
4293 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) {
4294 ALL_JAVA_THREADS(p) {
4295 p->oops_do(f, cf);
4296 }
4297 VMThread::vm_thread()->oops_do(f, cf);
4298 }
4299
4300 void Threads::change_thread_claim_parity() {
4301 // Set the new claim parity.
4302 assert(_thread_claim_parity >= 0 && _thread_claim_parity <= 2,
4303 "Not in range.");
4304 _thread_claim_parity++;
4305 if (_thread_claim_parity == 3) _thread_claim_parity = 1;
4378 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
4379 virtual void do_thread(Thread* thread) {
4380 thread->metadata_handles_do(_f);
4381 }
4382 };
4383
4384 void Threads::metadata_handles_do(void f(Metadata*)) {
4385 // Only walk the Handles in Thread.
4386 ThreadHandlesClosure handles_closure(f);
4387 threads_do(&handles_closure);
4388 }
4389
4390 void Threads::deoptimized_wrt_marked_nmethods() {
4391 ALL_JAVA_THREADS(p) {
4392 p->deoptimized_wrt_marked_nmethods();
4393 }
4394 }
4395
4396
4397 // Get count Java threads that are waiting to enter the specified monitor.
4398 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
4399 address monitor,
4400 bool doLock) {
4401 assert(doLock || SafepointSynchronize::is_at_safepoint(),
4402 "must grab Threads_lock or be at safepoint");
4403 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
4404
4405 int i = 0;
4406 {
4407 MutexLockerEx ml(doLock ? Threads_lock : NULL);
4408 ALL_JAVA_THREADS(p) {
4409 if (!p->can_call_java()) continue;
4410
4411 address pending = (address)p->current_pending_monitor();
4412 if (pending == monitor) { // found a match
4413 if (i < count) result->append(p); // save the first count matches
4414 i++;
4415 }
4416 }
4417 }
4418 return result;
4419 }
4420
4421
4422 JavaThread *Threads::owning_thread_from_monitor_owner(address owner,
4423 bool doLock) {
4424 assert(doLock ||
4425 Threads_lock->owned_by_self() ||
4426 SafepointSynchronize::is_at_safepoint(),
4427 "must grab Threads_lock or be at safepoint");
4428
4429 // NULL owner means not locked so we can skip the search
4430 if (owner == NULL) return NULL;
4431
4432 {
4433 MutexLockerEx ml(doLock ? Threads_lock : NULL);
4434 ALL_JAVA_THREADS(p) {
4435 // first, see if owner is the address of a Java thread
4436 if (owner == (address)p) return p;
4437 }
4438 }
4439 // Cannot assert on lack of success here since this function may be
4440 // used by code that is trying to report useful problem information
4441 // like deadlock detection.
4442 if (UseHeavyMonitors) return NULL;
4443
4444 // If we didn't find a matching Java thread and we didn't force use of
4445 // heavyweight monitors, then the owner is the stack address of the
4446 // Lock Word in the owning Java thread's stack.
4447 //
4448 JavaThread* the_owner = NULL;
4449 {
4450 MutexLockerEx ml(doLock ? Threads_lock : NULL);
4451 ALL_JAVA_THREADS(q) {
4452 if (q->is_lock_owned(owner)) {
4453 the_owner = q;
4454 break;
4455 }
4456 }
4457 }
4458 // cannot assert on lack of success here; see above comment
4459 return the_owner;
4460 }
4461
4462 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
4463 void Threads::print_on(outputStream* st, bool print_stacks,
4464 bool internal_format, bool print_concurrent_locks) {
4465 char buf[32];
4466 st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
4467
4468 st->print_cr("Full thread dump %s (%s %s):",
4469 Abstract_VM_Version::vm_name(),
4470 Abstract_VM_Version::vm_release(),
4471 Abstract_VM_Version::vm_info_string());
4472 st->cr();
4473
4474 #if INCLUDE_SERVICES
4475 // Dump concurrent locks
4476 ConcurrentLocksDump concurrent_locks;
4477 if (print_concurrent_locks) {
4478 concurrent_locks.dump_at_safepoint();
4479 }
4480 #endif // INCLUDE_SERVICES
4481
4482 ALL_JAVA_THREADS(p) {
4483 ResourceMark rm;
4484 p->print_on(st);
4485 if (print_stacks) {
4486 if (internal_format) {
4487 p->trace_stack();
4488 } else {
4489 p->print_stack_on(st);
4490 }
4491 }
4492 st->cr();
4493 #if INCLUDE_SERVICES
4494 if (print_concurrent_locks) {
4495 concurrent_locks.print_locks_on(p, st);
4496 }
4497 #endif // INCLUDE_SERVICES
4498 }
4499
4500 VMThread::vm_thread()->print_on(st);
4501 st->cr();
4502 Universe::heap()->print_gc_threads_on(st);
4503 WatcherThread* wt = WatcherThread::watcher_thread();
4504 if (wt != NULL) {
4505 wt->print_on(st);
4506 st->cr();
4507 }
4508 st->flush();
4509 }
4510
4511 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
4512 int buflen, bool* found_current) {
4513 if (this_thread != NULL) {
4514 bool is_current = (current == this_thread);
4515 *found_current = *found_current || is_current;
4516 st->print("%s", is_current ? "=>" : " ");
4517
4518 st->print(PTR_FORMAT, p2i(this_thread));
4519 st->print(" ");
4520 this_thread->print_on_error(st, buf, buflen);
4521 st->cr();
4522 }
4523 }
4524
4525 class PrintOnErrorClosure : public ThreadClosure {
4526 outputStream* _st;
4527 Thread* _current;
4528 char* _buf;
4529 int _buflen;
4530 bool* _found_current;
4531 public:
4532 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf,
4533 int buflen, bool* found_current) :
4534 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {}
4535
4536 virtual void do_thread(Thread* thread) {
4537 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current);
4538 }
4539 };
4540
4541 // Threads::print_on_error() is called by fatal error handler. It's possible
4542 // that VM is not at safepoint and/or current thread is inside signal handler.
4543 // Don't print stack trace, as the stack may not be walkable. Don't allocate
4544 // memory (even in resource area), it might deadlock the error handler.
4545 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
4546 int buflen) {
4547 bool found_current = false;
4548 st->print_cr("Java Threads: ( => current thread )");
4549 ALL_JAVA_THREADS(thread) {
4550 print_on_error(thread, st, current, buf, buflen, &found_current);
4551 }
4552 st->cr();
4553
4554 st->print_cr("Other Threads:");
4555 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current);
4556 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current);
4557
4558 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
4559 Universe::heap()->gc_threads_do(&print_closure);
4560
4561 if (!found_current) {
4562 st->cr();
4563 st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
4564 current->print_on_error(st, buf, buflen);
4565 st->cr();
4566 }
4567 st->cr();
4568 st->print_cr("Threads with active compile tasks:");
4569 print_threads_compiling(st, buf, buflen);
4570 }
4571
4572 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen) {
4573 ALL_JAVA_THREADS(thread) {
4574 if (thread->is_Compiler_thread()) {
4575 CompilerThread* ct = (CompilerThread*) thread;
4576 if (ct->task() != NULL) {
4577 thread->print_name_on_error(st, buf, buflen);
4578 ct->task()->print(st, NULL, true, true);
4579 }
4580 }
4581 }
4582 }
4583
4584
4585 // Internal SpinLock and Mutex
4586 // Based on ParkEvent
4587
|
53 #include "oops/symbol.hpp"
54 #include "oops/verifyOopClosure.hpp"
55 #include "prims/jvm_misc.hpp"
56 #include "prims/jvmtiExport.hpp"
57 #include "prims/jvmtiThreadState.hpp"
58 #include "prims/privilegedStack.hpp"
59 #include "runtime/arguments.hpp"
60 #include "runtime/atomic.hpp"
61 #include "runtime/biasedLocking.hpp"
62 #include "runtime/commandLineFlagConstraintList.hpp"
63 #include "runtime/commandLineFlagWriteableList.hpp"
64 #include "runtime/commandLineFlagRangeList.hpp"
65 #include "runtime/deoptimization.hpp"
66 #include "runtime/frame.inline.hpp"
67 #include "runtime/globals.hpp"
68 #include "runtime/init.hpp"
69 #include "runtime/interfaceSupport.hpp"
70 #include "runtime/java.hpp"
71 #include "runtime/javaCalls.hpp"
72 #include "runtime/jniPeriodicChecker.hpp"
73 #include "runtime/memprofiler.hpp"
74 #include "runtime/mutexLocker.hpp"
75 #include "runtime/objectMonitor.hpp"
76 #include "runtime/orderAccess.inline.hpp"
77 #include "runtime/osThread.hpp"
78 #include "runtime/prefetch.inline.hpp"
79 #include "runtime/safepoint.hpp"
80 #include "runtime/sharedRuntime.hpp"
81 #include "runtime/statSampler.hpp"
82 #include "runtime/stubRoutines.hpp"
83 #include "runtime/sweeper.hpp"
84 #include "runtime/task.hpp"
85 #include "runtime/thread.inline.hpp"
86 #include "runtime/threadCritical.hpp"
87 #include "runtime/threadSMR.inline.hpp"
88 #include "runtime/timer.hpp"
89 #include "runtime/timerTrace.hpp"
90 #include "runtime/vframe.hpp"
91 #include "runtime/vframeArray.hpp"
92 #include "runtime/vframe_hp.hpp"
93 #include "runtime/vmThread.hpp"
94 #include "runtime/vm_operations.hpp"
95 #include "runtime/vm_version.hpp"
96 #include "services/attachListener.hpp"
97 #include "services/management.hpp"
98 #include "services/memTracker.hpp"
99 #include "services/threadService.hpp"
100 #include "trace/traceMacros.hpp"
101 #include "trace/tracing.hpp"
102 #include "utilities/align.hpp"
103 #include "utilities/defaultStream.hpp"
104 #include "utilities/dtrace.hpp"
105 #include "utilities/events.hpp"
106 #include "utilities/macros.hpp"
107 #include "utilities/preserveException.hpp"
108 #include "utilities/resourceHash.hpp"
109 #include "utilities/vmError.hpp"
110 #if INCLUDE_ALL_GCS
111 #include "gc/cms/concurrentMarkSweepThread.hpp"
112 #include "gc/g1/concurrentMarkThread.inline.hpp"
113 #include "gc/parallel/pcTasks.hpp"
114 #endif // INCLUDE_ALL_GCS
115 #if INCLUDE_JVMCI
116 #include "jvmci/jvmciCompiler.hpp"
117 #include "jvmci/jvmciRuntime.hpp"
118 #include "logging/logHandle.hpp"
119 #endif
120 #ifdef COMPILER1
121 #include "c1/c1_Compiler.hpp"
122 #endif
123 #ifdef COMPILER2
124 #include "opto/c2compiler.hpp"
125 #include "opto/idealGraphPrinter.hpp"
126 #endif
127 #if INCLUDE_RTM_OPT
128 #include "runtime/rtmLocking.hpp"
180 AllocFailStrategy::RETURN_NULL);
181 void* aligned_addr = align_up(real_malloc_addr, alignment);
182 assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
183 ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
184 "JavaThread alignment code overflowed allocated storage");
185 if (aligned_addr != real_malloc_addr) {
186 log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
187 p2i(real_malloc_addr),
188 p2i(aligned_addr));
189 }
190 ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
191 return aligned_addr;
192 } else {
193 return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
194 : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
195 }
196 }
197
198 void Thread::operator delete(void* p) {
199 if (UseBiasedLocking) {
200 FreeHeap(((Thread*) p)->_real_malloc_address);
201 } else {
202 FreeHeap(p);
203 }
204 }
205
206 void JavaThread::smr_delete() {
207 if (_on_thread_list) {
208 Threads::smr_delete(this);
209 } else {
210 delete this;
211 }
212 }
213
214 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
215 // JavaThread
216
217
218 Thread::Thread() {
219 // stack and get_thread
220 set_stack_base(NULL);
221 set_stack_size(0);
222 set_self_raw_id(0);
223 set_lgrp_id(-1);
224 DEBUG_ONLY(clear_suspendible_thread();)
225
226 // allocated data structures
227 set_osthread(NULL);
228 set_resource_area(new (mtThread)ResourceArea());
229 DEBUG_ONLY(_current_resource_mark = NULL;)
230 set_handle_area(new (mtThread) HandleArea(NULL));
231 set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
232 set_active_handles(NULL);
233 set_free_handle_block(NULL);
234 set_last_handle_mark(NULL);
235
236 // This initial value ==> never claimed.
237 _oops_do_parity = 0;
238 _threads_hazard_ptr = NULL;
239 _nested_threads_hazard_ptr = NULL;
240 _nested_threads_hazard_ptr_cnt = 0;
241
242 // the handle mark links itself to last_handle_mark
243 new HandleMark(this);
244
245 // plain initialization
246 debug_only(_owned_locks = NULL;)
247 debug_only(_allow_allocation_count = 0;)
248 NOT_PRODUCT(_allow_safepoint_count = 0;)
249 NOT_PRODUCT(_skip_gcalot = false;)
250 _jvmti_env_iteration_count = 0;
251 set_allocated_bytes(0);
252 _vm_operation_started_count = 0;
253 _vm_operation_completed_count = 0;
254 _current_pending_monitor = NULL;
255 _current_pending_monitor_is_from_java = true;
256 _current_waiting_monitor = NULL;
257 _num_nested_signal = 0;
258 omFreeList = NULL;
259 omFreeCount = 0;
260 omFreeProvision = 32;
392 _SR_lock = NULL;
393
394 // osthread() can be NULL, if creation of thread failed.
395 if (osthread() != NULL) os::free_thread(osthread());
396
397 // clear Thread::current if thread is deleting itself.
398 // Needed to ensure JNI correctly detects non-attached threads.
399 if (this == Thread::current()) {
400 clear_thread_current();
401 }
402
403 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
404 }
405
406 // NOTE: dummy function for assertion purpose.
407 void Thread::run() {
408 ShouldNotReachHere();
409 }
410
411 #ifdef ASSERT
412 // A JavaThread is considered "dangling" if it is not the current
413 // thread, has been added the Threads list, the system is not at a
414 // safepoint and the Thread is not "protected".
415 //
416 void Thread::check_for_dangling_thread_pointer(Thread *thread) {
417 assert(!thread->is_Java_thread() || Thread::current() == thread ||
418 !((JavaThread *) thread)->on_thread_list() ||
419 SafepointSynchronize::is_at_safepoint() ||
420 Threads::is_a_protected_JavaThread_with_lock((JavaThread *) thread),
421 "possibility of dangling Thread pointer");
422 }
423 #endif
424
425 ThreadPriority Thread::get_priority(const Thread* const thread) {
426 ThreadPriority priority;
427 // Can return an error!
428 (void)os::get_priority(thread, priority);
429 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
430 return priority;
431 }
432
433 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
434 debug_only(check_for_dangling_thread_pointer(thread);)
435 // Can return an error!
436 (void)os::set_priority(thread, priority);
437 }
438
439
440 void Thread::start(Thread* thread) {
732
733 if (!pending) {
734 // A cancelled suspend request is the only false return from
735 // is_ext_suspend_completed() that keeps us from staying in the
736 // retry loop.
737 *bits |= 0x00080000;
738 return false;
739 }
740
741 if (is_suspended) {
742 *bits |= 0x00100000;
743 return true;
744 }
745 } // end retry loop
746
747 // thread did not suspend after all our retries
748 *bits |= 0x00200000;
749 return false;
750 }
751
752 // Called from API entry points which perform stack walking. If the
753 // associated JavaThread is the current thread, then wait_for_suspend
754 // is not used. Otherwise, it determines if we should wait for the
755 // "other" thread to complete external suspension. (NOTE: in future
756 // releases the suspension mechanism should be reimplemented so this
757 // is not necessary.)
758 //
759 bool
760 JavaThread::is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits) {
761 if (this != JavaThread::current()) {
762 // "other" threads require special handling.
763 if (wait_for_suspend) {
764 // We are allowed to wait for the external suspend to complete
765 // so give the other thread a chance to get suspended.
766 if (!wait_for_ext_suspend_completion(SuspendRetryCount,
767 SuspendRetryDelay, bits)) {
768 // Didn't make it so let the caller know.
769 return false;
770 }
771 }
772 // We aren't allowed to wait for the external suspend to complete
773 // so if the other thread isn't externally suspended we need to
774 // let the caller know.
775 else if (!is_ext_suspend_completed_with_lock(bits)) {
776 return false;
777 }
778 }
779
780 return true;
781 }
782
783 #ifndef PRODUCT
784 void JavaThread::record_jump(address target, address instr, const char* file,
785 int line) {
786
787 // This should not need to be atomic as the only way for simultaneous
788 // updates is via interrupts. Even then this should be rare or non-existent
789 // and we don't care that much anyway.
790
791 int index = _jmp_ring_index;
792 _jmp_ring_index = (index + 1) & (jump_ring_buffer_size - 1);
793 _jmp_ring[index]._target = (intptr_t) target;
794 _jmp_ring[index]._instruction = (intptr_t) instr;
795 _jmp_ring[index]._file = file;
796 _jmp_ring[index]._line = line;
797 }
798 #endif // PRODUCT
799
800 void Thread::interrupt(Thread* thread) {
801 debug_only(check_for_dangling_thread_pointer(thread);)
802 os::interrupt(thread);
841 void Thread::metadata_handles_do(void f(Metadata*)) {
842 // Only walk the Handles in Thread.
843 if (metadata_handles() != NULL) {
844 for (int i = 0; i< metadata_handles()->length(); i++) {
845 f(metadata_handles()->at(i));
846 }
847 }
848 }
849
850 void Thread::print_on(outputStream* st) const {
851 // get_priority assumes osthread initialized
852 if (osthread() != NULL) {
853 int os_prio;
854 if (os::get_native_priority(this, &os_prio) == OS_OK) {
855 st->print("os_prio=%d ", os_prio);
856 }
857 st->print("tid=" INTPTR_FORMAT " ", p2i(this));
858 ext().print_on(st);
859 osthread()->print_on(st);
860 }
861 if (_threads_hazard_ptr != NULL) {
862 st->print("_threads_hazard_ptr=" INTPTR_FORMAT, p2i(_threads_hazard_ptr));
863 }
864 if (_nested_threads_hazard_ptr != NULL) {
865 print_nested_threads_hazard_ptrs_on(st);
866 }
867 st->print(" ");
868 debug_only(if (WizardMode) print_owned_locks_on(st);)
869 }
870
871 void Thread::print_nested_threads_hazard_ptrs_on(outputStream* st) const {
872 assert(_nested_threads_hazard_ptr != NULL, "must be set to print");
873
874 if (EnableThreadSMRStatistics) {
875 st->print(", _nested_threads_hazard_ptr_cnt=%u", _nested_threads_hazard_ptr_cnt);
876 }
877 st->print(", _nested_threads_hazard_ptrs=");
878 for (NestedThreadsList* node = _nested_threads_hazard_ptr; node != NULL;
879 node = node->next()) {
880 if (node != _nested_threads_hazard_ptr) {
881 // First node does not need a comma-space separator.
882 st->print(", ");
883 }
884 st->print(INTPTR_FORMAT, p2i(node->t_list()));
885 }
886 }
887
888 // Thread::print_on_error() is called by fatal error handler. Don't use
889 // any lock or allocate memory.
890 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
891 assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates");
892
893 if (is_VM_thread()) { st->print("VMThread"); }
894 else if (is_GC_task_thread()) { st->print("GCTaskThread"); }
895 else if (is_Watcher_thread()) { st->print("WatcherThread"); }
896 else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); }
897 else { st->print("Thread"); }
898
899 if (is_Named_thread()) {
900 st->print(" \"%s\"", name());
901 }
902
903 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
904 p2i(stack_end()), p2i(stack_base()));
905
906 if (osthread()) {
907 st->print(" [id=%d]", osthread()->thread_id());
908 }
909
910 if (_threads_hazard_ptr != NULL) {
911 st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(_threads_hazard_ptr));
912 }
913 if (_nested_threads_hazard_ptr != NULL) {
914 print_nested_threads_hazard_ptrs_on(st);
915 }
916 }
917
918 void Thread::print_value_on(outputStream* st) const {
919 if (is_Named_thread()) {
920 st->print(" \"%s\" ", name());
921 }
922 st->print(INTPTR_FORMAT, p2i(this)); // print address
923 }
924
925 #ifdef ASSERT
926 void Thread::print_owned_locks_on(outputStream* st) const {
927 Monitor *cur = _owned_locks;
928 if (cur == NULL) {
929 st->print(" (no locks) ");
930 } else {
931 st->print_cr(" Locks owned:");
932 while (cur) {
933 cur->print_on(st);
934 cur = cur->next();
935 }
936 }
937 }
938
939 static int ref_use_count = 0;
940
941 bool Thread::owns_locks_but_compiled_lock() const {
942 for (Monitor *cur = _owned_locks; cur; cur = cur->next()) {
943 if (cur != Compile_lock) return true;
944 }
945 return false;
946 }
947
948
949 #endif
950
951 #ifndef PRODUCT
952
953 // The flag: potential_vm_operation notifies if this particular safepoint state could potentially
954 // invoke the vm-thread (e.g., an oop allocation). In that case, we also have to make sure that
955 // no threads which allow_vm_block's are held
956 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
957 // Check if current thread is allowed to block at a safepoint
958 if (!(_allow_safepoint_count == 0)) {
959 fatal("Possible safepoint reached by thread that does not allow it");
960 }
961 if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
962 fatal("LEAF method calling lock?");
963 }
964
965 #ifdef ASSERT
966 if (potential_vm_operation && is_Java_thread()
967 && !Universe::is_bootstrapping()) {
968 // Make sure we do not hold any locks that the VM thread also uses.
969 // This could potentially lead to deadlocks
970 for (Monitor *cur = _owned_locks; cur; cur = cur->next()) {
971 // Threads_lock is special, since the safepoint synchronization will not start before this is
972 // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock,
973 // since it is used to transfer control between JavaThreads and the VMThread
974 // Do not *exclude* any locks unless you are absolutely sure it is correct. Ask someone else first!
1460
1461 void WatcherThread::print_on(outputStream* st) const {
1462 st->print("\"%s\" ", name());
1463 Thread::print_on(st);
1464 st->cr();
1465 }
1466
1467 // ======= JavaThread ========
1468
1469 #if INCLUDE_JVMCI
1470
1471 jlong* JavaThread::_jvmci_old_thread_counters;
1472
1473 bool jvmci_counters_include(JavaThread* thread) {
1474 oop threadObj = thread->threadObj();
1475 return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
1476 }
1477
1478 void JavaThread::collect_counters(typeArrayOop array) {
1479 if (JVMCICounterSize > 0) {
1480 // dcubed - Looks like the Threads_lock is for stable access
1481 // to _jvmci_old_thread_counters and _jvmci_counters.
1482 MutexLocker tl(Threads_lock);
1483 JavaThreadIteratorWithHandle jtiwh;
1484 for (int i = 0; i < array->length(); i++) {
1485 array->long_at_put(i, _jvmci_old_thread_counters[i]);
1486 }
1487 for (; JavaThread *tp = jtiwh.next(); ) {
1488 if (jvmci_counters_include(tp)) {
1489 for (int i = 0; i < array->length(); i++) {
1490 array->long_at_put(i, array->long_at(i) + tp->_jvmci_counters[i]);
1491 }
1492 }
1493 }
1494 }
1495 }
1496
1497 #endif // INCLUDE_JVMCI
1498
1499 // A JavaThread is a normal Java thread
1500
1501 void JavaThread::initialize() {
1502 // Initialize fields
1503
1504 set_saved_exception_pc(NULL);
1505 set_threadObj(NULL);
1506 _anchor.clear();
1507 set_entry_point(NULL);
1508 set_jni_functions(jni_functions());
1509 set_callee_target(NULL);
1510 set_vm_result(NULL);
1511 set_vm_result_2(NULL);
1512 set_vframe_array_head(NULL);
1513 set_vframe_array_last(NULL);
1514 set_deferred_locals(NULL);
1515 set_deopt_mark(NULL);
1516 set_deopt_compiled_method(NULL);
1517 clear_must_deopt_id();
1518 set_monitor_chunks(NULL);
1519 set_next(NULL);
1520 _on_thread_list = false;
1521 set_thread_state(_thread_new);
1522 _terminated = _not_terminated;
1523 _privileged_stack_top = NULL;
1524 _array_for_gc = NULL;
1525 _suspend_equivalent = false;
1526 _in_deopt_handler = 0;
1527 _doing_unsafe_access = false;
1528 _stack_guard_state = stack_guard_unused;
1529 #if INCLUDE_JVMCI
1530 _pending_monitorenter = false;
1531 _pending_deoptimization = -1;
1532 _pending_failed_speculation = NULL;
1533 _pending_transfer_to_interpreter = false;
1534 _adjusting_comp_level = false;
1535 _jvmci._alternate_call_target = NULL;
1536 assert(_jvmci._implicit_exception_pc == NULL, "must be");
1537 if (JVMCICounterSize > 0) {
1538 _jvmci_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal);
1539 memset(_jvmci_counters, 0, sizeof(jlong) * JVMCICounterSize);
1540 } else {
1777 void JavaThread::thread_main_inner() {
1778 assert(JavaThread::current() == this, "sanity check");
1779 assert(this->threadObj() != NULL, "just checking");
1780
1781 // Execute thread entry point unless this thread has a pending exception
1782 // or has been stopped before starting.
1783 // Note: Due to JVM_StopThread we can have pending exceptions already!
1784 if (!this->has_pending_exception() &&
1785 !java_lang_Thread::is_stillborn(this->threadObj())) {
1786 {
1787 ResourceMark rm(this);
1788 this->set_native_thread_name(this->get_thread_name());
1789 }
1790 HandleMark hm(this);
1791 this->entry_point()(this, this);
1792 }
1793
1794 DTRACE_THREAD_PROBE(stop, this);
1795
1796 this->exit(false);
1797 this->smr_delete();
1798 }
1799
1800
1801 static void ensure_join(JavaThread* thread) {
1802 // We do not need to grab the Threads_lock, since we are operating on ourself.
1803 Handle threadObj(thread, thread->threadObj());
1804 assert(threadObj.not_null(), "java thread object must exist");
1805 ObjectLocker lock(threadObj, thread);
1806 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1807 thread->clear_pending_exception();
1808 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
1809 java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1810 // Clear the native thread instance - this makes isAlive return false and allows the join()
1811 // to complete once we've done the notify_all below
1812 java_lang_Thread::set_thread(threadObj(), NULL);
1813 lock.notify_all(thread);
1814 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1815 thread->clear_pending_exception();
1816 }
1817
1818
1819 // For any new cleanup additions, please check to see if they need to be applied to
1820 // cleanup_failed_attach_current_thread as well.
1821 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
1822 assert(this == JavaThread::current(), "thread consistency check");
1823
1824 elapsedTimer _timer_exit_phase1;
1825 elapsedTimer _timer_exit_phase2;
1826 elapsedTimer _timer_exit_phase3;
1827 elapsedTimer _timer_exit_phase4;
1828
1829 if (log_is_enabled(Debug, os, thread, timer)) {
1830 _timer_exit_phase1.start();
1831 }
1832
1833 HandleMark hm(this);
1834 Handle uncaught_exception(this, this->pending_exception());
1835 this->clear_pending_exception();
1836 Handle threadObj(this, this->threadObj());
1837 assert(threadObj.not_null(), "Java thread object should be created");
1838
1839 // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place
1840 {
1841 EXCEPTION_MARK;
1842
1843 CLEAR_PENDING_EXCEPTION;
1844 }
1845 if (!destroy_vm) {
1846 if (uncaught_exception.not_null()) {
1847 EXCEPTION_MARK;
1848 // Call method Thread.dispatchUncaughtException().
1849 Klass* thread_klass = SystemDictionary::Thread_klass();
1850 JavaValue result(T_VOID);
1851 JavaCalls::call_virtual(&result,
1852 threadObj, thread_klass,
1912 // Implied else:
1913 // Things get a little tricky here. We have a pending external
1914 // suspend request, but we are holding the SR_lock so we
1915 // can't just self-suspend. So we temporarily drop the lock
1916 // and then self-suspend.
1917 }
1918
1919 ThreadBlockInVM tbivm(this);
1920 java_suspend_self();
1921
1922 // We're done with this suspend request, but we have to loop around
1923 // and check again. Eventually we will get SR_lock without a pending
1924 // external suspend request and will be able to mark ourselves as
1925 // exiting.
1926 }
1927 // no more external suspends are allowed at this point
1928 } else {
1929 // before_exit() has already posted JVMTI THREAD_END events
1930 }
1931
1932 if (log_is_enabled(Debug, os, thread, timer)) {
1933 _timer_exit_phase1.stop();
1934 _timer_exit_phase2.start();
1935 }
1936 // Notify waiters on thread object. This has to be done after exit() is called
1937 // on the thread (if the thread is the last thread in a daemon ThreadGroup the
1938 // group should have the destroyed bit set before waiters are notified).
1939 ensure_join(this);
1940 assert(!this->has_pending_exception(), "ensure_join should have cleared");
1941
1942 if (log_is_enabled(Debug, os, thread, timer)) {
1943 _timer_exit_phase2.stop();
1944 _timer_exit_phase3.start();
1945 }
1946 // 6282335 JNI DetachCurrentThread spec states that all Java monitors
1947 // held by this thread must be released. The spec does not distinguish
1948 // between JNI-acquired and regular Java monitors. We can only see
1949 // regular Java monitors here if monitor enter-exit matching is broken.
1950 //
1951 // Optionally release any monitors for regular JavaThread exits. This
1952 // is provided as a work around for any bugs in monitor enter-exit
1953 // matching. This can be expensive so it is not enabled by default.
1954 //
1955 // ensure_join() ignores IllegalThreadStateExceptions, and so does
1956 // ObjectSynchronizer::release_monitors_owned_by_thread().
1957 if (exit_type == jni_detach || ObjectMonitor::Knob_ExitRelease) {
1958 // Sanity check even though JNI DetachCurrentThread() would have
1959 // returned JNI_ERR if there was a Java frame. JavaThread exit
1960 // should be done executing Java code by the time we get here.
1961 assert(!this->has_last_Java_frame(),
1962 "should not have a Java frame when detaching or exiting");
1963 ObjectSynchronizer::release_monitors_owned_by_thread(this);
1964 assert(!this->has_pending_exception(), "release_monitors should have cleared");
1965 }
1993
1994 // We must flush any deferred card marks before removing a thread from
1995 // the list of active threads.
1996 Universe::heap()->flush_deferred_store_barrier(this);
1997 assert(deferred_card_mark().is_empty(), "Should have been flushed");
1998
1999 #if INCLUDE_ALL_GCS
2000 // We must flush the G1-related buffers before removing a thread
2001 // from the list of active threads. We must do this after any deferred
2002 // card marks have been flushed (above) so that any entries that are
2003 // added to the thread's dirty card queue as a result are not lost.
2004 if (UseG1GC) {
2005 flush_barrier_queues();
2006 }
2007 #endif // INCLUDE_ALL_GCS
2008
2009 log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").",
2010 exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
2011 os::current_thread_id());
2012
2013 if (log_is_enabled(Debug, os, thread, timer)) {
2014 _timer_exit_phase3.stop();
2015 _timer_exit_phase4.start();
2016 }
2017 // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
2018 Threads::remove(this);
2019
2020 if (log_is_enabled(Debug, os, thread, timer)) {
2021 _timer_exit_phase4.stop();
2022 ResourceMark rm(this);
2023 log_debug(os, thread, timer)("name='%s'"
2024 ", exit-phase1=" JLONG_FORMAT
2025 ", exit-phase2=" JLONG_FORMAT
2026 ", exit-phase3=" JLONG_FORMAT
2027 ", exit-phase4=" JLONG_FORMAT,
2028 get_thread_name(),
2029 _timer_exit_phase1.milliseconds(),
2030 _timer_exit_phase2.milliseconds(),
2031 _timer_exit_phase3.milliseconds(),
2032 _timer_exit_phase4.milliseconds());
2033 }
2034 }
2035
2036 #if INCLUDE_ALL_GCS
2037 // Flush G1-related queues.
2038 void JavaThread::flush_barrier_queues() {
2039 satb_mark_queue().flush();
2040 dirty_card_queue().flush();
2041 }
2042
2043 void JavaThread::initialize_queues() {
2044 assert(!SafepointSynchronize::is_at_safepoint(),
2045 "we should not be at a safepoint");
2046
2047 SATBMarkQueue& satb_queue = satb_mark_queue();
2048 SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set();
2049 // The SATB queue should have been constructed with its active
2050 // field set to false.
2051 assert(!satb_queue.is_active(), "SATB queue should not be active");
2052 assert(satb_queue.is_empty(), "SATB queue should be empty");
2053 // If we are creating the thread during a marking cycle, we should
2073 if (free_handle_block() != NULL) {
2074 JNIHandleBlock* block = free_handle_block();
2075 set_free_handle_block(NULL);
2076 JNIHandleBlock::release_block(block);
2077 }
2078
2079 // These have to be removed while this is still a valid thread.
2080 remove_stack_guard_pages();
2081
2082 if (UseTLAB) {
2083 tlab().make_parsable(true); // retire TLAB, if any
2084 }
2085
2086 #if INCLUDE_ALL_GCS
2087 if (UseG1GC) {
2088 flush_barrier_queues();
2089 }
2090 #endif // INCLUDE_ALL_GCS
2091
2092 Threads::remove(this);
2093 this->smr_delete();
2094 }
2095
2096
2097
2098
2099 JavaThread* JavaThread::active() {
2100 Thread* thread = Thread::current();
2101 if (thread->is_Java_thread()) {
2102 return (JavaThread*) thread;
2103 } else {
2104 assert(thread->is_VM_thread(), "this must be a vm thread");
2105 VM_Operation* op = ((VMThread*) thread)->vm_operation();
2106 JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
2107 assert(ret->is_Java_thread(), "must be a Java thread");
2108 return ret;
2109 }
2110 }
2111
2112 bool JavaThread::is_lock_owned(address adr) const {
2113 if (Thread::is_lock_owned(adr)) return true;
2328 }
2329
2330
2331 // Interrupt thread so it will wake up from a potential wait()
2332 Thread::interrupt(this);
2333 }
2334
2335 // External suspension mechanism.
2336 //
2337 // Tell the VM to suspend a thread when ever it knows that it does not hold on
2338 // to any VM_locks and it is at a transition
2339 // Self-suspension will happen on the transition out of the vm.
2340 // Catch "this" coming in from JNIEnv pointers when the thread has been freed
2341 //
2342 // Guarantees on return:
2343 // + Target thread will not execute any new bytecode (that's why we need to
2344 // force a safepoint)
2345 // + Target thread will not enter any new monitors
2346 //
2347 void JavaThread::java_suspend() {
2348 ThreadsListHandle tlh;
2349 if (!tlh.includes(this) || threadObj() == NULL || is_exiting()) {
2350 return;
2351 }
2352
2353 { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2354 if (!is_external_suspend()) {
2355 // a racing resume has cancelled us; bail out now
2356 return;
2357 }
2358
2359 // suspend is done
2360 uint32_t debug_bits = 0;
2361 // Warning: is_ext_suspend_completed() may temporarily drop the
2362 // SR_lock to allow the thread to reach a stable thread state if
2363 // it is currently in a transient thread state.
2364 if (is_ext_suspend_completed(false /* !called_by_wait */,
2365 SuspendRetryDelay, &debug_bits)) {
2366 return;
2367 }
2368 }
2369
2370 VM_ThreadSuspend vm_suspend;
2371 VMThread::execute(&vm_suspend);
2419 // it. This would be a "bad thing (TM)" and cause the stack walker
2420 // to crash. We stay self-suspended until there are no more pending
2421 // external suspend requests.
2422 while (is_external_suspend()) {
2423 ret++;
2424 this->set_ext_suspended();
2425
2426 // _ext_suspended flag is cleared by java_resume()
2427 while (is_ext_suspended()) {
2428 this->SR_lock()->wait(Mutex::_no_safepoint_check_flag);
2429 }
2430 }
2431
2432 return ret;
2433 }
2434
2435 #ifdef ASSERT
2436 // verify the JavaThread has not yet been published in the Threads::list, and
2437 // hence doesn't need protection from concurrent access at this stage
2438 void JavaThread::verify_not_published() {
2439 ThreadsListHandle tlh;
2440 assert(!tlh.includes(this), "JavaThread shouldn't have been published yet!");
2441 }
2442 #endif
2443
2444 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2445 // progress or when _suspend_flags is non-zero.
2446 // Current thread needs to self-suspend if there is a suspend request and/or
2447 // block if a safepoint is in progress.
2448 // Async exception ISN'T checked.
2449 // Note only the ThreadInVMfromNative transition can call this function
2450 // directly and when thread state is _thread_in_native_trans
2451 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
2452 assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
2453
2454 JavaThread *curJT = JavaThread::current();
2455 bool do_self_suspend = thread->is_external_suspend();
2456
2457 assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
2458
2459 // If JNIEnv proxies are allowed, don't self-suspend if the target
2460 // thread is not the current thread. In older versions of jdbx, jdbx
2541 check_special_condition_for_native_trans(thread);
2542
2543 // Finish the transition
2544 thread->set_thread_state(_thread_in_Java);
2545
2546 if (thread->do_critical_native_unlock()) {
2547 ThreadInVMfromJavaNoAsyncException tiv(thread);
2548 GCLocker::unlock_critical(thread);
2549 thread->clear_critical_native_unlock();
2550 }
2551 }
2552
2553 // We need to guarantee the Threads_lock here, since resumes are not
2554 // allowed during safepoint synchronization
2555 // Can only resume from an external suspension
2556 void JavaThread::java_resume() {
2557 assert_locked_or_safepoint(Threads_lock);
2558
2559 // Sanity check: thread is gone, has started exiting or the thread
2560 // was not externally suspended.
2561 ThreadsListHandle tlh;
2562 if (!tlh.includes(this) || is_exiting() || !is_external_suspend()) {
2563 return;
2564 }
2565
2566 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2567
2568 clear_external_suspend();
2569
2570 if (is_ext_suspended()) {
2571 clear_ext_suspended();
2572 SR_lock()->notify_all();
2573 }
2574 }
2575
2576 size_t JavaThread::_stack_red_zone_size = 0;
2577 size_t JavaThread::_stack_yellow_zone_size = 0;
2578 size_t JavaThread::_stack_reserved_zone_size = 0;
2579 size_t JavaThread::_stack_shadow_zone_size = 0;
2580
2581 void JavaThread::create_stack_guard_pages() {
2582 if (!os::uses_stack_guard_pages() || _stack_guard_state != stack_guard_unused) { return; }
3010 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
3011 st->print("%s", get_thread_name_string(buf, buflen));
3012 }
3013
3014 // Called by fatal error handler. The difference between this and
3015 // JavaThread::print() is that we can't grab lock or allocate memory.
3016 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
3017 st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
3018 oop thread_obj = threadObj();
3019 if (thread_obj != NULL) {
3020 if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
3021 }
3022 st->print(" [");
3023 st->print("%s", _get_thread_state_name(_thread_state));
3024 if (osthread()) {
3025 st->print(", id=%d", osthread()->thread_id());
3026 }
3027 st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
3028 p2i(stack_end()), p2i(stack_base()));
3029 st->print("]");
3030
3031 if (_threads_hazard_ptr != NULL) {
3032 st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(_threads_hazard_ptr));
3033 }
3034 if (_nested_threads_hazard_ptr != NULL) {
3035 print_nested_threads_hazard_ptrs_on(st);
3036 }
3037 return;
3038 }
3039
3040 // Verification
3041
3042 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
3043
3044 void JavaThread::verify() {
3045 // Verify oops in the thread.
3046 oops_do(&VerifyOopClosure::verify_oop, NULL);
3047
3048 // Verify the stack frames.
3049 frames_do(frame_verify);
3050 }
3051
3052 // CR 6300358 (sub-CR 2137150)
3053 // Most callers of this method assume that it can't return NULL but a
3054 // thread may not have a name whilst it is in the process of attaching to
3055 // the VM - see CR 6412693, and there are places where a JavaThread can be
3056 // seen prior to having it's threadObj set (eg JNI attaching threads and
3421 // a scan.
3422 cf->do_code_blob(_scanned_compiled_method);
3423 }
3424 }
3425
3426
3427 // ======= Threads ========
3428
3429 // The Threads class links together all active threads, and provides
3430 // operations over all threads. It is protected by its own Mutex
3431 // lock, which is also used in other contexts to protect thread
3432 // operations from having the thread being operated on from exiting
3433 // and going away unexpectedly (e.g., safepoint synchronization)
3434
3435 JavaThread* Threads::_thread_list = NULL;
3436 int Threads::_number_of_threads = 0;
3437 int Threads::_number_of_non_daemon_threads = 0;
3438 int Threads::_return_code = 0;
3439 int Threads::_thread_claim_parity = 0;
3440 size_t JavaThread::_stack_size_at_create = 0;
3441 Monitor* Threads::_smr_delete_lock =
3442 new Monitor(Monitor::special, "smr_delete_lock",
3443 false /* allow_vm_block */,
3444 Monitor::_safepoint_check_never);
3445 // The '_cnt', '_max' and '_times" fields are enabled via
3446 // -XX:+EnableThreadSMRStatistics:
3447 uint Threads::_smr_delete_lock_wait_cnt = 0;
3448 uint Threads::_smr_delete_lock_wait_max = 0;
3449 volatile jint Threads::_smr_delete_notify = 0;
3450 volatile jint Threads::_smr_deleted_thread_cnt = 0;
3451 volatile jint Threads::_smr_deleted_thread_time_max = 0;
3452 volatile jint Threads::_smr_deleted_thread_times = 0;
3453 ThreadsList* volatile Threads::_smr_java_thread_list = new ThreadsList(0);
3454 long Threads::_smr_java_thread_list_alloc_cnt = 1;
3455 long Threads::_smr_java_thread_list_free_cnt = 0;
3456 uint Threads::_smr_java_thread_list_max = 0;
3457 uint Threads::_smr_nested_thread_list_max = 0;
3458 volatile jint Threads::_smr_tlh_cnt = 0;
3459 volatile jint Threads::_smr_tlh_time_max = 0;
3460 volatile jint Threads::_smr_tlh_times = 0;
3461 ThreadsList* Threads::_smr_to_delete_list = NULL;
3462 uint Threads::_smr_to_delete_list_cnt = 0;
3463 uint Threads::_smr_to_delete_list_max = 0;
3464
3465 #ifdef ASSERT
3466 bool Threads::_vm_complete = false;
3467 #endif
3468
3469 static inline void *prefetch_and_load_ptr(void **addr, intx prefetch_interval) {
3470 Prefetch::read((void*)addr, prefetch_interval);
3471 return *addr;
3472 }
3473
3474 // Possibly the ugliest for loop the world has seen. C++ does not allow
3475 // multiple types in the declaration section of the for loop. In this case
3476 // we are only dealing with pointers and hence can cast them. It looks ugly
3477 // but macros are ugly and therefore it's fine to make things absurdly ugly.
3478 #define DO_JAVA_THREADS(LIST, X) \
3479 for (JavaThread *MACRO_scan_interval = (JavaThread*)(uintptr_t)PrefetchScanIntervalInBytes, \
3480 *MACRO_list = (JavaThread*)(LIST), \
3481 **MACRO_end = ((JavaThread**)((ThreadsList*)MACRO_list)->threads()) + ((ThreadsList*)MACRO_list)->length(), \
3482 **MACRO_current_p = (JavaThread**)((ThreadsList*)MACRO_list)->threads(), \
3483 *X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval); \
3484 MACRO_current_p != MACRO_end; \
3485 MACRO_current_p++, \
3486 X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval))
3487
3488 // All JavaThreads
3489 #define ALL_JAVA_THREADS(X) DO_JAVA_THREADS(get_smr_java_thread_list(), X)
3490
3491 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
3492 void Threads::threads_do(ThreadClosure* tc) {
3493 assert_locked_or_safepoint(Threads_lock);
3494 // ALL_JAVA_THREADS iterates through all JavaThreads
3495 ALL_JAVA_THREADS(p) {
3496 tc->do_thread(p);
3497 }
3498 // Someday we could have a table or list of all non-JavaThreads.
3499 // For now, just manually iterate through them.
3500 tc->do_thread(VMThread::vm_thread());
3501 Universe::heap()->gc_threads_do(tc);
3502 WatcherThread *wt = WatcherThread::watcher_thread();
3503 // Strictly speaking, the following NULL check isn't sufficient to make sure
3504 // the data for WatcherThread is still valid upon being examined. However,
3505 // considering that WatchThread terminates when the VM is on the way to
3506 // exit at safepoint, the chance of the above is extremely small. The right
3507 // way to prevent termination of WatcherThread would be to acquire
3508 // Terminator_lock, but we can't do that without violating the lock rank
3509 // checking in some cases.
3570 if (result.get_jint() != JNI_OK) {
3571 vm_exit_during_initialization(); // no message or exception
3572 }
3573
3574 universe_post_module_init();
3575 }
3576
3577 // Phase 3. final setup - set security manager, system class loader and TCCL
3578 //
3579 // This will instantiate and set the security manager, set the system class
3580 // loader as well as the thread context class loader. The security manager
3581 // and system class loader may be a custom class loaded from -Xbootclasspath/a,
3582 // other modules or the application's classpath.
3583 static void call_initPhase3(TRAPS) {
3584 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3585 JavaValue result(T_VOID);
3586 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
3587 vmSymbols::void_method_signature(), CHECK);
3588 }
3589
3590 // Safe Memory Reclamation (SMR) support:
3591 //
3592
3593 // Acquire a stable ThreadsList.
3594 //
3595 ThreadsList *Threads::acquire_stable_list(Thread *self, bool is_ThreadsListSetter) {
3596 assert(self != NULL, "sanity check");
3597 // acquire_stable_list_nested_path() will grab the Threads_lock
3598 // so let's make sure the ThreadsListHandle is in a safe place.
3599 // ThreadsListSetter cannot make this check on this code path.
3600 debug_only(if (!is_ThreadsListSetter && StrictSafepointChecks) self->check_for_valid_safepoint_state(/* potential_vm_operation */ false);)
3601
3602 if (self->get_threads_hazard_ptr() == NULL) {
3603 // The typical case is first.
3604 return acquire_stable_list_fast_path(self);
3605 }
3606
3607 // The nested case is rare.
3608 return acquire_stable_list_nested_path(self);
3609 }
3610
3611 // Fast path (and lock free) way to acquire a stable ThreadsList.
3612 //
3613 ThreadsList *Threads::acquire_stable_list_fast_path(Thread *self) {
3614 assert(self != NULL, "sanity check");
3615 assert(self->get_threads_hazard_ptr() == NULL, "sanity check");
3616 assert(self->get_nested_threads_hazard_ptr() == NULL,
3617 "cannot have a nested hazard ptr with a NULL regular hazard ptr");
3618
3619 ThreadsList* threads;
3620
3621 // Stable recording of a hazard ptr for SMR. This code does not use
3622 // locks so its use of the _smr_java_thread_list & _threads_hazard_ptr
3623 // fields is racy relative to code that uses those fields with locks.
3624 // OrderAccess and Atomic functions are used to deal with those races.
3625 //
3626 while (true) {
3627 threads = get_smr_java_thread_list();
3628
3629 // Publish a tagged hazard ptr to denote that the hazard ptr is not
3630 // yet verified as being stable. Due to the fence after the hazard
3631 // ptr write, it will be sequentially consistent w.r.t. the
3632 // sequentially consistent writes of the ThreadsList, even on
3633 // non-multiple copy atomic machines where stores can be observed
3634 // in different order from different observer threads.
3635 ThreadsList* unverified_threads = Thread::tag_hazard_ptr(threads);
3636 self->set_threads_hazard_ptr(unverified_threads);
3637
3638 // If _smr_java_thread_list has changed, we have lost a race with
3639 // Threads::add() or Threads::remove() and have to try again.
3640 if (get_smr_java_thread_list() != threads) {
3641 continue;
3642 }
3643
3644 // We try to remove the tag which will verify the hazard ptr as
3645 // being stable. This exchange can race with a scanning thread
3646 // which might invalidate the tagged hazard ptr to keep it from
3647 // being followed to access JavaThread ptrs. If we lose the race,
3648 // we simply retry. If we win the race, then the stable hazard
3649 // ptr is officially published.
3650 if (self->cmpxchg_threads_hazard_ptr(threads, unverified_threads) == unverified_threads) {
3651 break;
3652 }
3653 }
3654
3655 // A stable hazard ptr has been published letting other threads know
3656 // that the ThreadsList and the JavaThreads reachable from this list
3657 // are protected and hence they should not be deleted until everyone
3658 // agrees it is safe to do so.
3659
3660 return threads;
3661 }
3662
3663 // Acquire a nested stable ThreadsList; this is rare so it uses
3664 // Threads_lock.
3665 //
3666 ThreadsList *Threads::acquire_stable_list_nested_path(Thread *self) {
3667 assert(self != NULL, "sanity check");
3668 assert(self->get_threads_hazard_ptr() != NULL,
3669 "cannot have a NULL regular hazard ptr when acquiring a nested hazard ptr");
3670
3671 // The thread already has a hazard ptr (ThreadsList ref) so we need
3672 // to create a nested ThreadsListHandle with the current ThreadsList
3673 // since it might be different than our current hazard ptr. The need
3674 // for a nested ThreadsListHandle is rare so we do this while holding
3675 // the Threads_lock so we don't race with the scanning code; the code
3676 // is so much simpler this way.
3677
3678 NestedThreadsList* node;
3679 {
3680 // Only grab the Threads_lock if we don't already own it.
3681 MutexLockerEx ml(Threads_lock->owned_by_self() ? NULL : Threads_lock);
3682 node = new NestedThreadsList(get_smr_java_thread_list());
3683 // We insert at the front of the list to match up with the delete
3684 // in release_stable_list().
3685 node->set_next(self->get_nested_threads_hazard_ptr());
3686 self->set_nested_threads_hazard_ptr(node);
3687 if (EnableThreadSMRStatistics) {
3688 self->inc_nested_threads_hazard_ptr_cnt();
3689 if (self->nested_threads_hazard_ptr_cnt() > _smr_nested_thread_list_max) {
3690 _smr_nested_thread_list_max = self->nested_threads_hazard_ptr_cnt();
3691 }
3692 }
3693 }
3694 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::acquire_stable_list: add NestedThreadsList node containing ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(node->t_list()));
3695
3696 return node->t_list();
3697 }
3698
3699 // Release a stable ThreadsList.
3700 //
3701 void Threads::release_stable_list(Thread *self) {
3702 assert(self != NULL, "sanity check");
3703 // release_stable_list_nested_path() will grab the Threads_lock
3704 // so let's make sure the ThreadsListHandle is in a safe place.
3705 debug_only(if (StrictSafepointChecks) self->check_for_valid_safepoint_state(/* potential_vm_operation */ false);)
3706
3707 if (self->get_nested_threads_hazard_ptr() == NULL) {
3708 // The typical case is first.
3709 release_stable_list_fast_path(self);
3710 return;
3711 }
3712
3713 // The nested case is rare.
3714 release_stable_list_nested_path(self);
3715 }
3716
3717 // Fast path way to release a stable ThreadsList. The release portion
3718 // is lock-free, but the wake up portion is not.
3719 //
3720 void Threads::release_stable_list_fast_path(Thread *self) {
3721 assert(self != NULL, "sanity check");
3722 assert(self->get_threads_hazard_ptr() != NULL, "sanity check");
3723 assert(self->get_nested_threads_hazard_ptr() == NULL,
3724 "cannot have a nested hazard ptr when releasing a regular hazard ptr");
3725
3726 // After releasing the hazard ptr, other threads may go ahead and
3727 // free up some memory temporarily used by a ThreadsList snapshot.
3728 self->set_threads_hazard_ptr(NULL);
3729
3730 // We use double-check locking to reduce traffic on the system
3731 // wide smr_delete_lock.
3732 if (Threads::smr_delete_notify()) {
3733 // An exiting thread might be waiting in smr_delete(); we need to
3734 // check with smr_delete_lock to be sure.
3735 release_stable_list_wake_up((char *) "regular hazard ptr");
3736 }
3737 }
3738
3739 // Release a nested stable ThreadsList; this is rare so it uses
3740 // Threads_lock.
3741 //
3742 void Threads::release_stable_list_nested_path(Thread *self) {
3743 assert(self != NULL, "sanity check");
3744 assert(self->get_nested_threads_hazard_ptr() != NULL, "sanity check");
3745 assert(self->get_threads_hazard_ptr() != NULL,
3746 "must have a regular hazard ptr to have nested hazard ptrs");
3747
3748 // We have a nested ThreadsListHandle so we have to release it first.
3749 // The need for a nested ThreadsListHandle is rare so we do this while
3750 // holding the Threads_lock so we don't race with the scanning code;
3751 // the code is so much simpler this way.
3752
3753 NestedThreadsList *node;
3754 {
3755 // Only grab the Threads_lock if we don't already own it.
3756 MutexLockerEx ml(Threads_lock->owned_by_self() ? NULL : Threads_lock);
3757 // We remove from the front of the list to match up with the insert
3758 // in acquire_stable_list().
3759 node = self->get_nested_threads_hazard_ptr();
3760 self->set_nested_threads_hazard_ptr(node->next());
3761 if (EnableThreadSMRStatistics) {
3762 self->dec_nested_threads_hazard_ptr_cnt();
3763 }
3764 }
3765
3766 // An exiting thread might be waiting in smr_delete(); we need to
3767 // check with smr_delete_lock to be sure.
3768 release_stable_list_wake_up((char *) "nested hazard ptr");
3769
3770 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::release_stable_list: delete NestedThreadsList node containing ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(node->t_list()));
3771
3772 delete node;
3773 }
3774
3775 // Wake up portion of the release stable ThreadsList protocol;
3776 // uses the smr_delete_lock().
3777 //
3778 void Threads::release_stable_list_wake_up(char *log_str) {
3779 assert(log_str != NULL, "sanity check");
3780
3781 // Note: smr_delete_lock is held in smr_delete() for the entire
3782 // hazard ptr search so that we do not lose this notify() if
3783 // the exiting thread has to wait. That code path also holds
3784 // Threads_lock (which was grabbed before smr_delete_lock) so that
3785 // threads_do() can be called. This means the system can't start a
3786 // safepoint which means this thread can't take too long to get to
3787 // a safepoint because of being blocked on smr_delete_lock.
3788 //
3789 MonitorLockerEx ml(Threads::smr_delete_lock(), Monitor::_no_safepoint_check_flag);
3790 if (Threads::smr_delete_notify()) {
3791 // Notify any exiting JavaThreads that are waiting in smr_delete()
3792 // that we've released a ThreadsList.
3793 ml.notify_all();
3794 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::release_stable_list notified %s", os::current_thread_id(), log_str);
3795 }
3796 }
3797
3798 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
3799 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
3800
3801 if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
3802 create_vm_init_libraries();
3803 }
3804
3805 initialize_class(vmSymbols::java_lang_String(), CHECK);
3806
3807 // Inject CompactStrings value after the static initializers for String ran.
3808 java_lang_String::set_compact_strings(CompactStrings);
3809
3810 // Initialize java_lang.System (needed before creating the thread)
3811 initialize_class(vmSymbols::java_lang_System(), CHECK);
3812 // The VM creates & returns objects of this class. Make sure it's initialized.
3813 initialize_class(vmSymbols::java_lang_Class(), CHECK);
3814 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
3815 Handle thread_group = create_initial_thread_group(CHECK);
3816 Universe::set_main_thread_group(thread_group());
3817 initialize_class(vmSymbols::java_lang_Thread(), CHECK);
3956 #if INCLUDE_JVMCI
3957 if (JVMCICounterSize > 0) {
3958 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal);
3959 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
3960 } else {
3961 JavaThread::_jvmci_old_thread_counters = NULL;
3962 }
3963 #endif // INCLUDE_JVMCI
3964
3965 // Attach the main thread to this os thread
3966 JavaThread* main_thread = new JavaThread();
3967 main_thread->set_thread_state(_thread_in_vm);
3968 main_thread->initialize_thread_current();
3969 // must do this before set_active_handles
3970 main_thread->record_stack_base_and_size();
3971 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
3972
3973 if (!main_thread->set_as_starting_thread()) {
3974 vm_shutdown_during_initialization(
3975 "Failed necessary internal allocation. Out of swap space");
3976 main_thread->smr_delete();
3977 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3978 return JNI_ENOMEM;
3979 }
3980
3981 // Enable guard page *after* os::create_main_thread(), otherwise it would
3982 // crash Linux VM, see notes in os_linux.cpp.
3983 main_thread->create_stack_guard_pages();
3984
3985 // Initialize Java-Level synchronization subsystem
3986 ObjectMonitor::Initialize();
3987
3988 // Initialize global modules
3989 jint status = init_globals();
3990 if (status != JNI_OK) {
3991 main_thread->smr_delete();
3992 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3993 return status;
3994 }
3995
3996 if (TRACE_INITIALIZE() != JNI_OK) {
3997 vm_exit_during_initialization("Failed to initialize tracing backend");
3998 }
3999
4000 // Should be done after the heap is fully created
4001 main_thread->cache_global_variables();
4002
4003 HandleMark hm;
4004
4005 { MutexLocker mu(Threads_lock);
4006 Threads::add(main_thread);
4007 }
4008
4009 // Any JVMTI raw monitors entered in onload will transition into
4010 // real raw monitor. VM is setup enough here for raw monitor enter.
4011 JvmtiExport::transition_pending_onload_raw_monitors();
4377 AgentLibrary* agent;
4378
4379 for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
4380 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
4381
4382 if (on_load_entry != NULL) {
4383 // Invoke the JVM_OnLoad function
4384 JavaThread* thread = JavaThread::current();
4385 ThreadToNativeFromVM ttn(thread);
4386 HandleMark hm(thread);
4387 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
4388 if (err != JNI_OK) {
4389 vm_exit_during_initialization("-Xrun library failed to init", agent->name());
4390 }
4391 } else {
4392 vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
4393 }
4394 }
4395 }
4396
4397
4398 // Last thread running calls java.lang.Shutdown.shutdown()
4399 void JavaThread::invoke_shutdown_hooks() {
4400 HandleMark hm(this);
4401
4402 // We could get here with a pending exception, if so clear it now.
4403 if (this->has_pending_exception()) {
4404 this->clear_pending_exception();
4405 }
4406
4407 EXCEPTION_MARK;
4408 Klass* shutdown_klass =
4409 SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
4410 THREAD);
4411 if (shutdown_klass != NULL) {
4412 // SystemDictionary::resolve_or_null will return null if there was
4413 // an exception. If we cannot load the Shutdown class, just don't
4414 // call Shutdown.shutdown() at all. This will mean the shutdown hooks
4415 // and finalizers (if runFinalizersOnExit is set) won't be run.
4416 // Note that if a shutdown hook was registered or runFinalizersOnExit
4417 // was called, the Shutdown class would have already been loaded
4502 VMThread::wait_for_vm_thread_exit();
4503 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
4504 VMThread::destroy();
4505 }
4506
4507 // clean up ideal graph printers
4508 #if defined(COMPILER2) && !defined(PRODUCT)
4509 IdealGraphPrinter::clean_up();
4510 #endif
4511
4512 // Now, all Java threads are gone except daemon threads. Daemon threads
4513 // running Java code or in VM are stopped by the Safepoint. However,
4514 // daemon threads executing native code are still running. But they
4515 // will be stopped at native=>Java/VM barriers. Note that we can't
4516 // simply kill or suspend them, as it is inherently deadlock-prone.
4517
4518 VM_Exit::set_vm_exited();
4519
4520 notify_vm_shutdown();
4521
4522 // We are after VM_Exit::set_vm_exited() so we can't call
4523 // thread->smr_delete() or we will block on the Threads_lock.
4524 // Deleting the shutdown thread here is safe because another
4525 // JavaThread cannot have an active ThreadsListHandle for
4526 // this JavaThread.
4527 delete thread;
4528
4529 #if INCLUDE_JVMCI
4530 if (JVMCICounterSize > 0) {
4531 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
4532 }
4533 #endif
4534
4535 // exit_globals() will delete tty
4536 exit_globals();
4537
4538 LogConfiguration::finalize();
4539
4540 return true;
4541 }
4542
4543
4544 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
4545 if (version == JNI_VERSION_1_1) return JNI_TRUE;
4546 return is_supported_jni_version(version);
4547 }
4548
4549
4550 jboolean Threads::is_supported_jni_version(jint version) {
4551 if (version == JNI_VERSION_1_2) return JNI_TRUE;
4552 if (version == JNI_VERSION_1_4) return JNI_TRUE;
4553 if (version == JNI_VERSION_1_6) return JNI_TRUE;
4554 if (version == JNI_VERSION_1_8) return JNI_TRUE;
4555 if (version == JNI_VERSION_9) return JNI_TRUE;
4556 if (version == JNI_VERSION_10) return JNI_TRUE;
4557 return JNI_FALSE;
4558 }
4559
4560 // Hash table of pointers found by a scan. Used for collecting hazard
4561 // pointers (ThreadsList references). Also used for collecting JavaThreads
4562 // that are indirectly referenced by hazard ptrs. An instance of this
4563 // class only contains one type of pointer.
4564 //
4565 class ThreadScanHashtable : public CHeapObj<mtThread> {
4566 private:
4567 static bool ptr_equals(void * const& s1, void * const& s2) {
4568 return s1 == s2;
4569 }
4570
4571 static unsigned int ptr_hash(void * const& s1) {
4572 return (unsigned int)(((uint32_t)(uintptr_t)s1) * 2654435761u);
4573 }
4574
4575 int _table_size;
4576 // ResourceHashtable SIZE is specified at compile time so our
4577 // dynamic _table_size is unused for now; 1031 is the first prime
4578 // after 1024.
4579 typedef ResourceHashtable<void *, int, &ThreadScanHashtable::ptr_hash,
4580 &ThreadScanHashtable::ptr_equals, 1031,
4581 ResourceObj::C_HEAP, mtThread> PtrTable;
4582 PtrTable * _ptrs;
4583
4584 public:
4585 // ResourceHashtable is passed to various functions and populated in
4586 // different places so we allocate it using C_HEAP to make it immune
4587 // from any ResourceMarks that happen to be in the code paths.
4588 ThreadScanHashtable(int table_size) : _table_size(table_size), _ptrs(new (ResourceObj::C_HEAP, mtThread) PtrTable()) {}
4589
4590 ~ThreadScanHashtable() { delete _ptrs; }
4591
4592 bool has_entry(void *pointer) {
4593 int *val_ptr = _ptrs->get(pointer);
4594 return val_ptr != NULL && *val_ptr == 1;
4595 }
4596
4597 void add_entry(void *pointer) {
4598 _ptrs->put(pointer, 1);
4599 }
4600 };
4601
4602 // Closure to gather JavaThreads indirectly referenced by hazard ptrs
4603 // (ThreadsList references) into a hash table. This closure handles part 2
4604 // of the dance - adding all the JavaThreads referenced by the hazard
4605 // pointer (ThreadsList reference) to the hash table.
4606 //
4607 class AddThreadHazardPointerThreadClosure : public ThreadClosure {
4608 private:
4609 ThreadScanHashtable *_table;
4610
4611 public:
4612 AddThreadHazardPointerThreadClosure(ThreadScanHashtable *table) : _table(table) {}
4613
4614 virtual void do_thread(Thread *thread) {
4615 if (!_table->has_entry((void*)thread)) {
4616 // The same JavaThread might be on more than one ThreadsList or
4617 // more than one thread might be using the same ThreadsList. In
4618 // either case, we only need a single entry for a JavaThread.
4619 _table->add_entry((void*)thread);
4620 }
4621 }
4622 };
4623
4624 // Closure to gather JavaThreads indirectly referenced by hazard ptrs
4625 // (ThreadsList references) into a hash table. This closure handles part 1
4626 // of the dance - hazard ptr chain walking and dispatch to another
4627 // closure.
4628 //
4629 class ScanHazardPtrGatherProtectedThreadsClosure : public ThreadClosure {
4630 private:
4631 ThreadScanHashtable *_table;
4632 public:
4633 ScanHazardPtrGatherProtectedThreadsClosure(ThreadScanHashtable *table) : _table(table) {}
4634
4635 virtual void do_thread(Thread *thread) {
4636 assert_locked_or_safepoint(Threads_lock);
4637
4638 if (thread == NULL) return;
4639
4640 // This code races with Threads::acquire_stable_list() which is
4641 // lock-free so we have to handle some special situations.
4642 //
4643 ThreadsList *current_list = NULL;
4644 while (true) {
4645 current_list = thread->get_threads_hazard_ptr();
4646 // No hazard ptr so nothing more to do.
4647 if (current_list == NULL) {
4648 assert(thread->get_nested_threads_hazard_ptr() == NULL,
4649 "cannot have a nested hazard ptr with a NULL regular hazard ptr");
4650 return;
4651 }
4652
4653 // If the hazard ptr is verified as stable (since it is not tagged),
4654 // then it is safe to use.
4655 if (!Thread::is_hazard_ptr_tagged(current_list)) break;
4656
4657 // The hazard ptr is tagged as not yet verified as being stable
4658 // so we are racing with acquire_stable_list(). This exchange
4659 // attempts to invalidate the hazard ptr. If we win the race,
4660 // then we can ignore this unstable hazard ptr and the other
4661 // thread will retry the attempt to publish a stable hazard ptr.
4662 // If we lose the race, then we retry our attempt to look at the
4663 // hazard ptr.
4664 if (thread->cmpxchg_threads_hazard_ptr(NULL, current_list) == current_list) return;
4665 }
4666
4667 // The current JavaThread has a hazard ptr (ThreadsList reference)
4668 // which might be _smr_java_thread_list or it might be an older
4669 // ThreadsList that has been removed but not freed. In either case,
4670 // the hazard ptr is protecting all the JavaThreads on that
4671 // ThreadsList.
4672 AddThreadHazardPointerThreadClosure add_cl(_table);
4673 current_list->threads_do(&add_cl);
4674
4675 // Any NestedThreadsLists are also protecting JavaThreads so
4676 // gather those also; the ThreadsLists may be different.
4677 for (NestedThreadsList* node = thread->get_nested_threads_hazard_ptr();
4678 node != NULL; node = node->next()) {
4679 node->t_list()->threads_do(&add_cl);
4680 }
4681 }
4682 };
4683
4684 // Closure to print JavaThreads that have a hazard ptr (ThreadsList
4685 // reference) that contains an indirect reference to a specific JavaThread.
4686 //
4687 class ScanHazardPtrPrintMatchingThreadsClosure : public ThreadClosure {
4688 private:
4689 JavaThread *_thread;
4690 public:
4691 ScanHazardPtrPrintMatchingThreadsClosure(JavaThread *thread) : _thread(thread) {}
4692
4693 virtual void do_thread(Thread *thread) {
4694 assert_locked_or_safepoint(Threads_lock);
4695
4696 if (thread == NULL) return;
4697 ThreadsList *current_list = thread->get_threads_hazard_ptr();
4698 if (current_list == NULL) {
4699 assert(thread->get_nested_threads_hazard_ptr() == NULL,
4700 "cannot have a nested hazard ptr with a NULL regular hazard ptr");
4701 return;
4702 }
4703 // If the hazard ptr is unverified, then ignore it.
4704 if (Thread::is_hazard_ptr_tagged(current_list)) return;
4705
4706 // The current JavaThread has a hazard ptr (ThreadsList reference)
4707 // which might be _smr_java_thread_list or it might be an older
4708 // ThreadsList that has been removed but not freed. In either case,
4709 // the hazard ptr is protecting all the JavaThreads on that
4710 // ThreadsList, but we only care about matching a specific JavaThread.
4711 DO_JAVA_THREADS(current_list, p) {
4712 if (p == _thread) {
4713 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_delete: thread1=" INTPTR_FORMAT " has a hazard pointer for thread2=" INTPTR_FORMAT, os::current_thread_id(), p2i(thread), p2i(_thread));
4714 break;
4715 }
4716 }
4717
4718 // Any NestedThreadsLists are also protecting JavaThreads so
4719 // check those also; the ThreadsLists may be different.
4720 for (NestedThreadsList* node = thread->get_nested_threads_hazard_ptr();
4721 node != NULL; node = node->next()) {
4722 DO_JAVA_THREADS(node->t_list(), p) {
4723 if (p == _thread) {
4724 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_delete: thread1=" INTPTR_FORMAT " has a nested hazard pointer for thread2=" INTPTR_FORMAT, os::current_thread_id(), p2i(thread), p2i(_thread));
4725 return;
4726 }
4727 }
4728 }
4729 }
4730 };
4731
4732 // Return true if the specified JavaThread is protected by a hazard
4733 // pointer (ThreadsList reference). Otherwise, returns false.
4734 //
4735 bool Threads::is_a_protected_JavaThread(JavaThread *thread) {
4736 assert_locked_or_safepoint(Threads_lock);
4737
4738 // Hash table size should be first power of two higher than twice
4739 // the length of the Threads list.
4740 int hash_table_size = MIN2(_number_of_threads, 32) << 1;
4741 hash_table_size--;
4742 hash_table_size |= hash_table_size >> 1;
4743 hash_table_size |= hash_table_size >> 2;
4744 hash_table_size |= hash_table_size >> 4;
4745 hash_table_size |= hash_table_size >> 8;
4746 hash_table_size |= hash_table_size >> 16;
4747 hash_table_size++;
4748
4749 // Gather a hash table of the JavaThreads indirectly referenced by
4750 // hazard ptrs.
4751 ThreadScanHashtable *scan_table = new ThreadScanHashtable(hash_table_size);
4752 ScanHazardPtrGatherProtectedThreadsClosure scan_cl(scan_table);
4753 Threads::threads_do(&scan_cl);
4754
4755 bool thread_is_protected = false;
4756 if (scan_table->has_entry((void*)thread)) {
4757 thread_is_protected = true;
4758 }
4759 delete scan_table;
4760 return thread_is_protected;
4761 }
4762
4763 // Safely delete a JavaThread when it is no longer in use by a
4764 // ThreadsListHandle.
4765 //
4766 void Threads::smr_delete(JavaThread *thread) {
4767 assert(!Threads_lock->owned_by_self(), "sanity");
4768
4769 bool has_logged_once = false;
4770 elapsedTimer timer;
4771 if (EnableThreadSMRStatistics) {
4772 timer.start();
4773 }
4774
4775 while (true) {
4776 {
4777 // No safepoint check because this JavaThread is not on the
4778 // Threads list.
4779 MutexLockerEx ml(Threads_lock, Mutex::_no_safepoint_check_flag);
4780 // Cannot use a MonitorLockerEx helper here because we have
4781 // to drop the Threads_lock first if we wait.
4782 Threads::smr_delete_lock()->lock_without_safepoint_check();
4783 // Set the smr_delete_notify flag after we grab smr_delete_lock
4784 // and before we scan hazard ptrs because we're doing
4785 // double-check locking in release_stable_list().
4786 Threads::set_smr_delete_notify();
4787
4788 if (!is_a_protected_JavaThread(thread)) {
4789 // This is the common case.
4790 Threads::clear_smr_delete_notify();
4791 Threads::smr_delete_lock()->unlock();
4792 break;
4793 }
4794 if (!has_logged_once) {
4795 has_logged_once = true;
4796 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_delete: thread=" INTPTR_FORMAT " is not deleted.", os::current_thread_id(), p2i(thread));
4797 if (log_is_enabled(Debug, os, thread)) {
4798 ScanHazardPtrPrintMatchingThreadsClosure scan_cl(thread);
4799 Threads::threads_do(&scan_cl);
4800 }
4801 }
4802 } // We have to drop the Threads_lock to wait or delete the thread
4803
4804 if (EnableThreadSMRStatistics) {
4805 _smr_delete_lock_wait_cnt++;
4806 if (_smr_delete_lock_wait_cnt > _smr_delete_lock_wait_max) {
4807 _smr_delete_lock_wait_max = _smr_delete_lock_wait_cnt;
4808 }
4809 }
4810 // Wait for a release_stable_list() call before we check again. No
4811 // safepoint check, no timeout, and not as suspend equivalent flag
4812 // because this JavaThread is not on the Threads list.
4813 Threads::smr_delete_lock()->wait(Mutex::_no_safepoint_check_flag, 0,
4814 !Mutex::_as_suspend_equivalent_flag);
4815 if (EnableThreadSMRStatistics) {
4816 _smr_delete_lock_wait_cnt--;
4817 }
4818
4819 Threads::clear_smr_delete_notify();
4820 Threads::smr_delete_lock()->unlock();
4821 // Retry the whole scenario.
4822 }
4823
4824 delete thread;
4825 if (EnableThreadSMRStatistics) {
4826 timer.stop();
4827 jint millis = (jint)timer.milliseconds();
4828 Threads::inc_smr_deleted_thread_cnt();
4829 Threads::add_smr_deleted_thread_times(millis);
4830 Threads::update_smr_deleted_thread_time_max(millis);
4831 }
4832
4833 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_delete: thread=" INTPTR_FORMAT " is deleted.", os::current_thread_id(), p2i(thread));
4834 }
4835
4836 bool Threads::smr_delete_notify() {
4837 // Use load_acquire() in order to see any updates to _smr_delete_notify
4838 // earlier than when smr_delete_lock is grabbed.
4839 return (OrderAccess::load_acquire(&_smr_delete_notify) != 0);
4840 }
4841
4842 // set_smr_delete_notify() and clear_smr_delete_notify() are called
4843 // under the protection of the smr_delete_lock, but we also use an
4844 // Atomic operation to ensure the memory update is seen earlier than
4845 // when the smr_delete_lock is dropped.
4846 //
4847 void Threads::set_smr_delete_notify() {
4848 Atomic::inc(&_smr_delete_notify);
4849 }
4850
4851 void Threads::clear_smr_delete_notify() {
4852 Atomic::dec(&_smr_delete_notify);
4853 }
4854
4855 // Closure to gather hazard ptrs (ThreadsList references) into a hash table.
4856 //
4857 class ScanHazardPtrGatherThreadsListClosure : public ThreadClosure {
4858 private:
4859 ThreadScanHashtable *_table;
4860 public:
4861 ScanHazardPtrGatherThreadsListClosure(ThreadScanHashtable *table) : _table(table) {}
4862
4863 virtual void do_thread(Thread* thread) {
4864 assert_locked_or_safepoint(Threads_lock);
4865
4866 if (thread == NULL) return;
4867 ThreadsList *threads = thread->get_threads_hazard_ptr();
4868 if (threads == NULL) {
4869 assert(thread->get_nested_threads_hazard_ptr() == NULL,
4870 "cannot have a nested hazard ptr with a NULL regular hazard ptr");
4871 return;
4872 }
4873 // In this closure we always ignore the tag that might mark this
4874 // hazard ptr as not yet verified. If we happen to catch an
4875 // unverified hazard ptr that is subsequently discarded (not
4876 // published), then the only side effect is that we might keep a
4877 // to-be-deleted ThreadsList alive a little longer.
4878 threads = Thread::untag_hazard_ptr(threads);
4879 if (!_table->has_entry((void*)threads)) {
4880 _table->add_entry((void*)threads);
4881 }
4882
4883 // Any NestedThreadsLists are also protecting JavaThreads so
4884 // gather those also; the ThreadsLists may be different.
4885 for (NestedThreadsList* node = thread->get_nested_threads_hazard_ptr();
4886 node != NULL; node = node->next()) {
4887 threads = node->t_list();
4888 if (!_table->has_entry((void*)threads)) {
4889 _table->add_entry((void*)threads);
4890 }
4891 }
4892 }
4893 };
4894
4895 // Safely free a ThreadsList after a Threads::add() or Threads::remove().
4896 // The specified ThreadsList may not get deleted during this call if it
4897 // is still in-use (referenced by a hazard ptr). Other ThreadsLists
4898 // in the chain may get deleted by this call if they are no longer in-use.
4899 void Threads::smr_free_list(ThreadsList* threads) {
4900 assert_locked_or_safepoint(Threads_lock);
4901
4902 threads->set_next_list(_smr_to_delete_list);
4903 _smr_to_delete_list = threads;
4904 if (EnableThreadSMRStatistics) {
4905 _smr_to_delete_list_cnt++;
4906 if (_smr_to_delete_list_cnt > _smr_to_delete_list_max) {
4907 _smr_to_delete_list_max = _smr_to_delete_list_cnt;
4908 }
4909 }
4910
4911 // Hash table size should be first power of two higher than twice the length of the ThreadsList
4912 int hash_table_size = MIN2(_number_of_threads, 32) << 1;
4913 hash_table_size--;
4914 hash_table_size |= hash_table_size >> 1;
4915 hash_table_size |= hash_table_size >> 2;
4916 hash_table_size |= hash_table_size >> 4;
4917 hash_table_size |= hash_table_size >> 8;
4918 hash_table_size |= hash_table_size >> 16;
4919 hash_table_size++;
4920
4921 // Gather a hash table of the current hazard ptrs:
4922 ThreadScanHashtable *scan_table = new ThreadScanHashtable(hash_table_size);
4923 ScanHazardPtrGatherThreadsListClosure scan_cl(scan_table);
4924 Threads::threads_do(&scan_cl);
4925
4926 // Walk through the linked list of pending freeable ThreadsLists
4927 // and free the ones that are not referenced from hazard ptrs.
4928 ThreadsList* current = _smr_to_delete_list;
4929 ThreadsList* prev = NULL;
4930 ThreadsList* next = NULL;
4931 bool threads_is_freed = false;
4932 while (current != NULL) {
4933 next = current->next_list();
4934 if (!scan_table->has_entry((void*)current)) {
4935 // This ThreadsList is not referenced by a hazard ptr.
4936 if (prev != NULL) {
4937 prev->set_next_list(next);
4938 }
4939 if (_smr_to_delete_list == current) {
4940 _smr_to_delete_list = next;
4941 }
4942
4943 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_free_list: threads=" INTPTR_FORMAT " is freed.", os::current_thread_id(), p2i(current));
4944 if (current == threads) threads_is_freed = true;
4945 delete current;
4946 if (EnableThreadSMRStatistics) {
4947 _smr_java_thread_list_free_cnt++;
4948 _smr_to_delete_list_cnt--;
4949 }
4950 } else {
4951 prev = current;
4952 }
4953 current = next;
4954 }
4955
4956 if (!threads_is_freed) {
4957 // Only report "is not freed" on the original call to
4958 // smr_free_list() for this ThreadsList.
4959 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_free_list: threads=" INTPTR_FORMAT " is not freed.", os::current_thread_id(), p2i(threads));
4960 }
4961
4962 delete scan_table;
4963 }
4964
4965 // Remove a JavaThread from a ThreadsList. The returned ThreadsList is a
4966 // new copy of the specified ThreadsList with the specified JavaThread
4967 // removed.
4968 ThreadsList *ThreadsList::remove_thread(ThreadsList* list, JavaThread* java_thread) {
4969 assert(list->_length > 0, "sanity");
4970
4971 uint i = 0;
4972 DO_JAVA_THREADS(list, current) {
4973 if (current == java_thread) {
4974 break;
4975 }
4976 i++;
4977 }
4978 assert(i < list->_length, "did not find JavaThread on the list");
4979 const uint index = i;
4980 const uint new_length = list->_length - 1;
4981 const uint head_length = index;
4982 const uint tail_length = (new_length >= index) ? (new_length - index) : 0;
4983 ThreadsList *const new_list = new ThreadsList(new_length);
4984
4985 if (head_length > 0) {
4986 Copy::disjoint_words((HeapWord*)list->_threads, (HeapWord*)new_list->_threads, head_length);
4987 }
4988 if (tail_length > 0) {
4989 Copy::disjoint_words((HeapWord*)list->_threads + index + 1, (HeapWord*)new_list->_threads + index, tail_length);
4990 }
4991
4992 return new_list;
4993 }
4994
4995 // Add a JavaThread to a ThreadsList. The returned ThreadsList is a
4996 // new copy of the specified ThreadsList with the specified JavaThread
4997 // appended to the end.
4998 ThreadsList *ThreadsList::add_thread(ThreadsList *list, JavaThread *java_thread) {
4999 const uint index = list->_length;
5000 const uint new_length = index + 1;
5001 const uint head_length = index;
5002 ThreadsList *const new_list = new ThreadsList(new_length);
5003
5004 if (head_length > 0) {
5005 Copy::disjoint_words((HeapWord*)list->_threads, (HeapWord*)new_list->_threads, head_length);
5006 }
5007 *(JavaThread**)(new_list->_threads + index) = java_thread;
5008
5009 return new_list;
5010 }
5011
5012 int ThreadsList::find_index_of_JavaThread(JavaThread *target) {
5013 if (target == NULL) {
5014 return -1;
5015 }
5016 for (uint i = 0; i < length(); i++) {
5017 if (target == thread_at(i)) {
5018 return (int)i;
5019 }
5020 }
5021 return -1;
5022 }
5023
5024 JavaThread* ThreadsList::find_JavaThread_from_java_tid(jlong java_tid) const {
5025 DO_JAVA_THREADS(this, thread) {
5026 oop tobj = thread->threadObj();
5027 // Ignore the thread if it hasn't run yet, has exited
5028 // or is starting to exit.
5029 if (tobj != NULL && !thread->is_exiting() &&
5030 java_tid == java_lang_Thread::thread_id(tobj)) {
5031 // found a match
5032 return thread;
5033 }
5034 }
5035 return NULL;
5036 }
5037
5038 bool ThreadsList::includes(const JavaThread * const p) const {
5039 if (p == NULL) {
5040 return false;
5041 }
5042 DO_JAVA_THREADS(this, q) {
5043 if (q == p) {
5044 return true;
5045 }
5046 }
5047 return false;
5048 }
5049
5050 void Threads::add(JavaThread* p, bool force_daemon) {
5051 // The threads lock must be owned at this point
5052 assert_locked_or_safepoint(Threads_lock);
5053
5054 // See the comment for this method in thread.hpp for its purpose and
5055 // why it is called here.
5056 p->initialize_queues();
5057 p->set_next(_thread_list);
5058 _thread_list = p;
5059
5060 // Once a JavaThread is added to the Threads list, smr_delete() has
5061 // to be used to delete it. Otherwise we can just delete it directly.
5062 p->set_on_thread_list();
5063
5064 _number_of_threads++;
5065 oop threadObj = p->threadObj();
5066 bool daemon = true;
5067 // Bootstrapping problem: threadObj can be null for initial
5068 // JavaThread (or for threads attached via JNI)
5069 if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) {
5070 _number_of_non_daemon_threads++;
5071 daemon = false;
5072 }
5073
5074 ThreadService::add_thread(p, daemon);
5075
5076 // Maintain fast thread list
5077 ThreadsList *new_list = ThreadsList::add_thread(get_smr_java_thread_list(), p);
5078 if (EnableThreadSMRStatistics) {
5079 _smr_java_thread_list_alloc_cnt++;
5080 if (new_list->length() > _smr_java_thread_list_max) {
5081 _smr_java_thread_list_max = new_list->length();
5082 }
5083 }
5084 // Initial _smr_java_thread_list will not generate a "Threads::add" mesg.
5085 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::add: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
5086
5087 ThreadsList *old_list = xchg_smr_java_thread_list(new_list);
5088 smr_free_list(old_list);
5089
5090 // Possible GC point.
5091 Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p));
5092 }
5093
5094 void Threads::remove(JavaThread* p) {
5095
5096 // Reclaim the objectmonitors from the omInUseList and omFreeList of the moribund thread.
5097 ObjectSynchronizer::omFlush(p);
5098
5099 // Extra scope needed for Thread_lock, so we can check
5100 // that we do not remove thread without safepoint code notice
5101 { MutexLocker ml(Threads_lock);
5102
5103 assert(get_smr_java_thread_list()->includes(p), "p must be present");
5104
5105 // Maintain fast thread list
5106 ThreadsList *new_list = ThreadsList::remove_thread(get_smr_java_thread_list(), p);
5107 if (EnableThreadSMRStatistics) {
5108 _smr_java_thread_list_alloc_cnt++;
5109 // This list is smaller so no need to check for a "longest" update.
5110 }
5111
5112 // Final _smr_java_thread_list will not generate a "Threads::remove" mesg.
5113 log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::remove: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
5114
5115 ThreadsList *old_list = xchg_smr_java_thread_list(new_list);
5116 smr_free_list(old_list);
5117
5118 JavaThread* current = _thread_list;
5119 JavaThread* prev = NULL;
5120
5121 while (current != p) {
5122 prev = current;
5123 current = current->next();
5124 }
5125
5126 if (prev) {
5127 prev->set_next(current->next());
5128 } else {
5129 _thread_list = p->next();
5130 }
5131
5132 _number_of_threads--;
5133 oop threadObj = p->threadObj();
5134 bool daemon = true;
5135 if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
5136 _number_of_non_daemon_threads--;
5137 daemon = false;
5138
5139 // Only one thread left, do a notify on the Threads_lock so a thread waiting
5140 // on destroy_vm will wake up.
5141 if (number_of_non_daemon_threads() == 1) {
5142 Threads_lock->notify_all();
5143 }
5144 }
5145 ThreadService::remove_thread(p, daemon);
5146
5147 // Make sure that safepoint code disregard this thread. This is needed since
5148 // the thread might mess around with locks after this point. This can cause it
5149 // to do callbacks into the safepoint code. However, the safepoint code is not aware
5150 // of this thread since it is removed from the queue.
5151 p->set_terminated_value();
5152 } // unlock Threads_lock
5153
5154 // Since Events::log uses a lock, we grab it outside the Threads_lock
5155 Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p));
5156 }
5157
5158 // Operations on the Threads list for GC. These are not explicitly locked,
5159 // but the garbage collector must provide a safe context for them to run.
5160 // In particular, these things should never be called when the Threads_lock
5161 // is held by some other thread. (Note: the Safepoint abstraction also
5162 // uses the Threads_lock to guarantee this property. It also makes sure that
5163 // all threads gets blocked when exiting or starting).
5164
5165 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) {
5166 ALL_JAVA_THREADS(p) {
5167 p->oops_do(f, cf);
5168 }
5169 VMThread::vm_thread()->oops_do(f, cf);
5170 }
5171
5172 void Threads::change_thread_claim_parity() {
5173 // Set the new claim parity.
5174 assert(_thread_claim_parity >= 0 && _thread_claim_parity <= 2,
5175 "Not in range.");
5176 _thread_claim_parity++;
5177 if (_thread_claim_parity == 3) _thread_claim_parity = 1;
5250 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
5251 virtual void do_thread(Thread* thread) {
5252 thread->metadata_handles_do(_f);
5253 }
5254 };
5255
5256 void Threads::metadata_handles_do(void f(Metadata*)) {
5257 // Only walk the Handles in Thread.
5258 ThreadHandlesClosure handles_closure(f);
5259 threads_do(&handles_closure);
5260 }
5261
5262 void Threads::deoptimized_wrt_marked_nmethods() {
5263 ALL_JAVA_THREADS(p) {
5264 p->deoptimized_wrt_marked_nmethods();
5265 }
5266 }
5267
5268
5269 // Get count Java threads that are waiting to enter the specified monitor.
5270 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list,
5271 int count,
5272 address monitor) {
5273 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
5274
5275 int i = 0;
5276 DO_JAVA_THREADS(t_list, p) {
5277 if (!p->can_call_java()) continue;
5278
5279 address pending = (address)p->current_pending_monitor();
5280 if (pending == monitor) { // found a match
5281 if (i < count) result->append(p); // save the first count matches
5282 i++;
5283 }
5284 }
5285
5286 return result;
5287 }
5288
5289
5290 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list,
5291 address owner) {
5292 // NULL owner means not locked so we can skip the search
5293 if (owner == NULL) return NULL;
5294
5295 DO_JAVA_THREADS(t_list, p) {
5296 // first, see if owner is the address of a Java thread
5297 if (owner == (address)p) return p;
5298 }
5299
5300 // Cannot assert on lack of success here since this function may be
5301 // used by code that is trying to report useful problem information
5302 // like deadlock detection.
5303 if (UseHeavyMonitors) return NULL;
5304
5305 // If we didn't find a matching Java thread and we didn't force use of
5306 // heavyweight monitors, then the owner is the stack address of the
5307 // Lock Word in the owning Java thread's stack.
5308 //
5309 JavaThread* the_owner = NULL;
5310 DO_JAVA_THREADS(t_list, q) {
5311 if (q->is_lock_owned(owner)) {
5312 the_owner = q;
5313 break;
5314 }
5315 }
5316
5317 // cannot assert on lack of success here; see above comment
5318 return the_owner;
5319 }
5320
5321 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
5322 void Threads::print_on(outputStream* st, bool print_stacks,
5323 bool internal_format, bool print_concurrent_locks) {
5324 char buf[32];
5325 st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
5326
5327 st->print_cr("Full thread dump %s (%s %s):",
5328 Abstract_VM_Version::vm_name(),
5329 Abstract_VM_Version::vm_release(),
5330 Abstract_VM_Version::vm_info_string());
5331 st->cr();
5332
5333 #if INCLUDE_SERVICES
5334 // Dump concurrent locks
5335 ConcurrentLocksDump concurrent_locks;
5336 if (print_concurrent_locks) {
5337 concurrent_locks.dump_at_safepoint();
5338 }
5339 #endif // INCLUDE_SERVICES
5340
5341 print_smr_info_on(st);
5342 st->cr();
5343
5344 ALL_JAVA_THREADS(p) {
5345 ResourceMark rm;
5346 p->print_on(st);
5347 if (print_stacks) {
5348 if (internal_format) {
5349 p->trace_stack();
5350 } else {
5351 p->print_stack_on(st);
5352 }
5353 }
5354 st->cr();
5355 #if INCLUDE_SERVICES
5356 if (print_concurrent_locks) {
5357 concurrent_locks.print_locks_on(p, st);
5358 }
5359 #endif // INCLUDE_SERVICES
5360 }
5361
5362 VMThread::vm_thread()->print_on(st);
5363 st->cr();
5364 Universe::heap()->print_gc_threads_on(st);
5365 WatcherThread* wt = WatcherThread::watcher_thread();
5366 if (wt != NULL) {
5367 wt->print_on(st);
5368 st->cr();
5369 }
5370
5371 st->flush();
5372 }
5373
5374 // Log Threads class SMR info.
5375 void Threads::log_smr_statistics() {
5376 LogTarget(Info, thread, smr) log;
5377 if (log.is_enabled()) {
5378 LogStream out(log);
5379 print_smr_info_on(&out);
5380 }
5381 }
5382
5383 // Print Threads class SMR info.
5384 void Threads::print_smr_info_on(outputStream* st) {
5385 // Only grab the Threads_lock if we don't already own it
5386 // and if we are not reporting an error.
5387 MutexLockerEx ml((Threads_lock->owned_by_self() || VMError::is_error_reported()) ? NULL : Threads_lock);
5388
5389 st->print_cr("Threads class SMR info:");
5390 st->print_cr("_smr_java_thread_list=" INTPTR_FORMAT ", length=%u, "
5391 "elements={", p2i(_smr_java_thread_list),
5392 _smr_java_thread_list->length());
5393 print_smr_info_elements_on(st, _smr_java_thread_list);
5394 st->print_cr("}");
5395 if (_smr_to_delete_list != NULL) {
5396 st->print_cr("_smr_to_delete_list=" INTPTR_FORMAT ", length=%u, "
5397 "elements={", p2i(_smr_to_delete_list),
5398 _smr_to_delete_list->length());
5399 print_smr_info_elements_on(st, _smr_to_delete_list);
5400 st->print_cr("}");
5401 for (ThreadsList *t_list = _smr_to_delete_list->next_list();
5402 t_list != NULL; t_list = t_list->next_list()) {
5403 st->print("next-> " INTPTR_FORMAT ", length=%u, "
5404 "elements={", p2i(t_list), t_list->length());
5405 print_smr_info_elements_on(st, t_list);
5406 st->print_cr("}");
5407 }
5408 }
5409 if (!EnableThreadSMRStatistics) {
5410 return;
5411 }
5412 st->print_cr("_smr_java_thread_list_alloc_cnt=%ld, "
5413 "_smr_java_thread_list_free_cnt=%ld, "
5414 "_smr_java_thread_list_max=%u, "
5415 "_smr_nested_thread_list_max=%u",
5416 _smr_java_thread_list_alloc_cnt,
5417 _smr_java_thread_list_free_cnt,
5418 _smr_java_thread_list_max,
5419 _smr_nested_thread_list_max);
5420 if (_smr_tlh_cnt > 0) {
5421 st->print_cr("_smr_tlh_cnt=" INT32_FORMAT
5422 ", _smr_tlh_times=" INT32_FORMAT
5423 ", avg_smr_tlh_time=%0.2f"
5424 ", _smr_tlh_time_max=" INT32_FORMAT,
5425 _smr_tlh_cnt, _smr_tlh_times,
5426 ((double) _smr_tlh_times / _smr_tlh_cnt),
5427 _smr_tlh_time_max);
5428 }
5429 if (_smr_deleted_thread_cnt > 0) {
5430 st->print_cr("_smr_deleted_thread_cnt=" INT32_FORMAT
5431 ", _smr_deleted_thread_times=" INT32_FORMAT
5432 ", avg_smr_deleted_thread_time=%0.2f"
5433 ", _smr_deleted_thread_time_max=" INT32_FORMAT,
5434 _smr_deleted_thread_cnt, _smr_deleted_thread_times,
5435 ((double) _smr_deleted_thread_times / _smr_deleted_thread_cnt),
5436 _smr_deleted_thread_time_max);
5437 }
5438 st->print_cr("_smr_delete_lock_wait_cnt=%u, _smr_delete_lock_wait_max=%u",
5439 _smr_delete_lock_wait_cnt, _smr_delete_lock_wait_max);
5440 st->print_cr("_smr_to_delete_list_cnt=%u, _smr_to_delete_list_max=%u",
5441 _smr_to_delete_list_cnt, _smr_to_delete_list_max);
5442 }
5443
5444 // Print ThreadsList elements (4 per line).
5445 void Threads::print_smr_info_elements_on(outputStream* st,
5446 ThreadsList* t_list) {
5447 uint cnt = 0;
5448 JavaThreadIterator jti(t_list);
5449 for (JavaThread *jt = jti.first(); jt != NULL; jt = jti.next()) {
5450 st->print(INTPTR_FORMAT, p2i(jt));
5451 if (cnt < t_list->length() - 1) {
5452 // Separate with comma or comma-space except for the last one.
5453 if (((cnt + 1) % 4) == 0) {
5454 // Four INTPTR_FORMAT fit on an 80 column line so end the
5455 // current line with just a comma.
5456 st->print_cr(",");
5457 } else {
5458 // Not the last one on the current line so use comma-space:
5459 st->print(", ");
5460 }
5461 } else {
5462 // Last one so just end the current line.
5463 st->cr();
5464 }
5465 cnt++;
5466 }
5467 }
5468
5469 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
5470 int buflen, bool* found_current) {
5471 if (this_thread != NULL) {
5472 bool is_current = (current == this_thread);
5473 *found_current = *found_current || is_current;
5474 st->print("%s", is_current ? "=>" : " ");
5475
5476 st->print(PTR_FORMAT, p2i(this_thread));
5477 st->print(" ");
5478 this_thread->print_on_error(st, buf, buflen);
5479 st->cr();
5480 }
5481 }
5482
5483 class PrintOnErrorClosure : public ThreadClosure {
5484 outputStream* _st;
5485 Thread* _current;
5486 char* _buf;
5487 int _buflen;
5488 bool* _found_current;
5489 public:
5490 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf,
5491 int buflen, bool* found_current) :
5492 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {}
5493
5494 virtual void do_thread(Thread* thread) {
5495 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current);
5496 }
5497 };
5498
5499 // Threads::print_on_error() is called by fatal error handler. It's possible
5500 // that VM is not at safepoint and/or current thread is inside signal handler.
5501 // Don't print stack trace, as the stack may not be walkable. Don't allocate
5502 // memory (even in resource area), it might deadlock the error handler.
5503 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
5504 int buflen) {
5505 print_smr_info_on(st);
5506 st->cr();
5507
5508 bool found_current = false;
5509 st->print_cr("Java Threads: ( => current thread )");
5510 ALL_JAVA_THREADS(thread) {
5511 print_on_error(thread, st, current, buf, buflen, &found_current);
5512 }
5513 st->cr();
5514
5515 st->print_cr("Other Threads:");
5516 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current);
5517 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current);
5518
5519 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
5520 Universe::heap()->gc_threads_do(&print_closure);
5521
5522 if (!found_current) {
5523 st->cr();
5524 st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
5525 current->print_on_error(st, buf, buflen);
5526 st->cr();
5527 }
5528 st->cr();
5529
5530 st->print_cr("Threads with active compile tasks:");
5531 print_threads_compiling(st, buf, buflen);
5532 }
5533
5534 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen) {
5535 ALL_JAVA_THREADS(thread) {
5536 if (thread->is_Compiler_thread()) {
5537 CompilerThread* ct = (CompilerThread*) thread;
5538 if (ct->task() != NULL) {
5539 thread->print_name_on_error(st, buf, buflen);
5540 ct->task()->print(st, NULL, true, true);
5541 }
5542 }
5543 }
5544 }
5545
5546
5547 // Internal SpinLock and Mutex
5548 // Based on ParkEvent
5549
|