aoqi@0: /* aoqi@0: * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. aoqi@0: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. aoqi@0: * aoqi@0: * This code is free software; you can redistribute it and/or modify it aoqi@0: * under the terms of the GNU General Public License version 2 only, as aoqi@0: * published by the Free Software Foundation. aoqi@0: * aoqi@0: * This code is distributed in the hope that it will be useful, but WITHOUT aoqi@0: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or aoqi@0: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License aoqi@0: * version 2 for more details (a copy is included in the LICENSE file that aoqi@0: * accompanied this code). aoqi@0: * aoqi@0: * You should have received a copy of the GNU General Public License version aoqi@0: * 2 along with this work; if not, write to the Free Software Foundation, aoqi@0: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. aoqi@0: * aoqi@0: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA aoqi@0: * or visit www.oracle.com if you need additional information or have any aoqi@0: * questions. aoqi@0: * aoqi@0: */ aoqi@0: aoqi@0: #include "precompiled.hpp" aoqi@0: #include "classfile/classLoader.hpp" aoqi@0: #include "classfile/javaClasses.hpp" aoqi@0: #include "classfile/systemDictionary.hpp" aoqi@0: #include "classfile/vmSymbols.hpp" aoqi@0: #include "code/scopeDesc.hpp" aoqi@0: #include "compiler/compileBroker.hpp" aoqi@0: #include "interpreter/interpreter.hpp" aoqi@0: #include "interpreter/linkResolver.hpp" aoqi@0: #include "interpreter/oopMapCache.hpp" aoqi@0: #include "jvmtifiles/jvmtiEnv.hpp" aoqi@0: #include "memory/gcLocker.inline.hpp" aoqi@0: #include "memory/metaspaceShared.hpp" aoqi@0: #include "memory/oopFactory.hpp" aoqi@0: #include "memory/universe.inline.hpp" aoqi@0: #include "oops/instanceKlass.hpp" aoqi@0: #include "oops/objArrayOop.hpp" aoqi@0: #include "oops/oop.inline.hpp" aoqi@0: #include "oops/symbol.hpp" aoqi@0: #include "prims/jvm_misc.hpp" aoqi@0: #include "prims/jvmtiExport.hpp" aoqi@0: #include "prims/jvmtiThreadState.hpp" aoqi@0: #include "prims/privilegedStack.hpp" aoqi@0: #include "runtime/arguments.hpp" aoqi@0: #include "runtime/biasedLocking.hpp" aoqi@0: #include "runtime/deoptimization.hpp" aoqi@0: #include "runtime/fprofiler.hpp" aoqi@0: #include "runtime/frame.inline.hpp" aoqi@0: #include "runtime/init.hpp" aoqi@0: #include "runtime/interfaceSupport.hpp" aoqi@0: #include "runtime/java.hpp" aoqi@0: #include "runtime/javaCalls.hpp" aoqi@0: #include "runtime/jniPeriodicChecker.hpp" aoqi@0: #include "runtime/memprofiler.hpp" aoqi@0: #include "runtime/mutexLocker.hpp" aoqi@0: #include "runtime/objectMonitor.hpp" aoqi@0: #include "runtime/osThread.hpp" aoqi@0: #include "runtime/safepoint.hpp" aoqi@0: #include "runtime/sharedRuntime.hpp" aoqi@0: #include "runtime/statSampler.hpp" aoqi@0: #include "runtime/stubRoutines.hpp" aoqi@0: #include "runtime/task.hpp" aoqi@0: #include "runtime/thread.inline.hpp" aoqi@0: #include "runtime/threadCritical.hpp" aoqi@0: #include "runtime/threadLocalStorage.hpp" aoqi@0: #include "runtime/vframe.hpp" aoqi@0: #include "runtime/vframeArray.hpp" aoqi@0: #include "runtime/vframe_hp.hpp" aoqi@0: #include "runtime/vmThread.hpp" aoqi@0: #include "runtime/vm_operations.hpp" aoqi@0: #include "services/attachListener.hpp" aoqi@0: #include "services/management.hpp" aoqi@0: #include "services/memTracker.hpp" aoqi@0: #include "services/threadService.hpp" aoqi@0: #include "trace/tracing.hpp" aoqi@0: #include "trace/traceMacros.hpp" aoqi@0: #include "utilities/defaultStream.hpp" aoqi@0: #include "utilities/dtrace.hpp" aoqi@0: #include "utilities/events.hpp" aoqi@0: #include "utilities/preserveException.hpp" aoqi@0: #include "utilities/macros.hpp" aoqi@0: #ifdef TARGET_OS_FAMILY_linux aoqi@0: # include "os_linux.inline.hpp" aoqi@0: #endif aoqi@0: #ifdef TARGET_OS_FAMILY_solaris aoqi@0: # include "os_solaris.inline.hpp" aoqi@0: #endif aoqi@0: #ifdef TARGET_OS_FAMILY_windows aoqi@0: # include "os_windows.inline.hpp" aoqi@0: #endif aoqi@0: #ifdef TARGET_OS_FAMILY_bsd aoqi@0: # include "os_bsd.inline.hpp" aoqi@0: #endif aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp" aoqi@0: #include "gc_implementation/g1/concurrentMarkThread.inline.hpp" aoqi@0: #include "gc_implementation/parallelScavenge/pcTasks.hpp" aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: #ifdef COMPILER1 aoqi@0: #include "c1/c1_Compiler.hpp" aoqi@0: #endif aoqi@0: #ifdef COMPILER2 aoqi@0: #include "opto/c2compiler.hpp" aoqi@0: #include "opto/idealGraphPrinter.hpp" aoqi@0: #endif aoqi@0: #if INCLUDE_RTM_OPT aoqi@0: #include "runtime/rtmLocking.hpp" aoqi@0: #endif aoqi@0: aoqi@0: PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC aoqi@0: aoqi@0: #ifdef DTRACE_ENABLED aoqi@0: aoqi@0: // Only bother with this argument setup if dtrace is available aoqi@0: aoqi@0: #ifndef USDT2 aoqi@0: HS_DTRACE_PROBE_DECL(hotspot, vm__init__begin); aoqi@0: HS_DTRACE_PROBE_DECL(hotspot, vm__init__end); aoqi@0: HS_DTRACE_PROBE_DECL5(hotspot, thread__start, char*, intptr_t, aoqi@0: intptr_t, intptr_t, bool); aoqi@0: HS_DTRACE_PROBE_DECL5(hotspot, thread__stop, char*, intptr_t, aoqi@0: intptr_t, intptr_t, bool); aoqi@0: aoqi@0: #define DTRACE_THREAD_PROBE(probe, javathread) \ aoqi@0: { \ aoqi@0: ResourceMark rm(this); \ aoqi@0: int len = 0; \ aoqi@0: const char* name = (javathread)->get_thread_name(); \ aoqi@0: len = strlen(name); \ aoqi@0: HS_DTRACE_PROBE5(hotspot, thread__##probe, \ aoqi@0: name, len, \ aoqi@0: java_lang_Thread::thread_id((javathread)->threadObj()), \ aoqi@0: (javathread)->osthread()->thread_id(), \ aoqi@0: java_lang_Thread::is_daemon((javathread)->threadObj())); \ aoqi@0: } aoqi@0: aoqi@0: #else /* USDT2 */ aoqi@0: aoqi@0: #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_PROBE_START aoqi@0: #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_PROBE_STOP aoqi@0: aoqi@0: #define DTRACE_THREAD_PROBE(probe, javathread) \ aoqi@0: { \ aoqi@0: ResourceMark rm(this); \ aoqi@0: int len = 0; \ aoqi@0: const char* name = (javathread)->get_thread_name(); \ aoqi@0: len = strlen(name); \ aoqi@0: HOTSPOT_THREAD_PROBE_##probe( /* probe = start, stop */ \ aoqi@0: (char *) name, len, \ aoqi@0: java_lang_Thread::thread_id((javathread)->threadObj()), \ aoqi@0: (uintptr_t) (javathread)->osthread()->thread_id(), \ aoqi@0: java_lang_Thread::is_daemon((javathread)->threadObj())); \ aoqi@0: } aoqi@0: aoqi@0: #endif /* USDT2 */ aoqi@0: aoqi@0: #else // ndef DTRACE_ENABLED aoqi@0: aoqi@0: #define DTRACE_THREAD_PROBE(probe, javathread) aoqi@0: aoqi@0: #endif // ndef DTRACE_ENABLED aoqi@0: aoqi@0: aoqi@0: // Class hierarchy aoqi@0: // - Thread aoqi@0: // - VMThread aoqi@0: // - WatcherThread aoqi@0: // - ConcurrentMarkSweepThread aoqi@0: // - JavaThread aoqi@0: // - CompilerThread aoqi@0: aoqi@0: // ======= Thread ======== aoqi@0: // Support for forcing alignment of thread objects for biased locking aoqi@0: void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) { aoqi@0: if (UseBiasedLocking) { aoqi@0: const int alignment = markOopDesc::biased_lock_alignment; aoqi@0: size_t aligned_size = size + (alignment - sizeof(intptr_t)); aoqi@0: void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC) aoqi@0: : AllocateHeap(aligned_size, flags, CURRENT_PC, aoqi@0: AllocFailStrategy::RETURN_NULL); aoqi@0: void* aligned_addr = (void*) align_size_up((intptr_t) real_malloc_addr, alignment); aoqi@0: assert(((uintptr_t) aligned_addr + (uintptr_t) size) <= aoqi@0: ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size), aoqi@0: "JavaThread alignment code overflowed allocated storage"); aoqi@0: if (TraceBiasedLocking) { aoqi@0: if (aligned_addr != real_malloc_addr) aoqi@0: tty->print_cr("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT, aoqi@0: real_malloc_addr, aligned_addr); aoqi@0: } aoqi@0: ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr; aoqi@0: return aligned_addr; aoqi@0: } else { aoqi@0: return throw_excpt? AllocateHeap(size, flags, CURRENT_PC) aoqi@0: : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void Thread::operator delete(void* p) { aoqi@0: if (UseBiasedLocking) { aoqi@0: void* real_malloc_addr = ((Thread*) p)->_real_malloc_address; aoqi@0: FreeHeap(real_malloc_addr, mtThread); aoqi@0: } else { aoqi@0: FreeHeap(p, mtThread); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread, aoqi@0: // JavaThread aoqi@0: aoqi@0: aoqi@0: Thread::Thread() { aoqi@0: // stack and get_thread aoqi@0: set_stack_base(NULL); aoqi@0: set_stack_size(0); aoqi@0: set_self_raw_id(0); aoqi@0: set_lgrp_id(-1); aoqi@0: aoqi@0: // allocated data structures aoqi@0: set_osthread(NULL); aoqi@0: set_resource_area(new (mtThread)ResourceArea()); aoqi@0: DEBUG_ONLY(_current_resource_mark = NULL;) aoqi@0: set_handle_area(new (mtThread) HandleArea(NULL)); aoqi@0: set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray(30, true)); aoqi@0: set_active_handles(NULL); aoqi@0: set_free_handle_block(NULL); aoqi@0: set_last_handle_mark(NULL); aoqi@0: aoqi@0: // This initial value ==> never claimed. aoqi@0: _oops_do_parity = 0; aoqi@0: aoqi@0: // the handle mark links itself to last_handle_mark aoqi@0: new HandleMark(this); aoqi@0: aoqi@0: // plain initialization aoqi@0: debug_only(_owned_locks = NULL;) aoqi@0: debug_only(_allow_allocation_count = 0;) aoqi@0: NOT_PRODUCT(_allow_safepoint_count = 0;) aoqi@0: NOT_PRODUCT(_skip_gcalot = false;) aoqi@0: _jvmti_env_iteration_count = 0; aoqi@0: set_allocated_bytes(0); aoqi@0: _vm_operation_started_count = 0; aoqi@0: _vm_operation_completed_count = 0; aoqi@0: _current_pending_monitor = NULL; aoqi@0: _current_pending_monitor_is_from_java = true; aoqi@0: _current_waiting_monitor = NULL; aoqi@0: _num_nested_signal = 0; aoqi@0: omFreeList = NULL ; aoqi@0: omFreeCount = 0 ; aoqi@0: omFreeProvision = 32 ; aoqi@0: omInUseList = NULL ; aoqi@0: omInUseCount = 0 ; aoqi@0: aoqi@0: #ifdef ASSERT aoqi@0: _visited_for_critical_count = false; aoqi@0: #endif aoqi@0: aoqi@0: _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true); aoqi@0: _suspend_flags = 0; aoqi@0: aoqi@0: // thread-specific hashCode stream generator state - Marsaglia shift-xor form aoqi@0: _hashStateX = os::random() ; aoqi@0: _hashStateY = 842502087 ; aoqi@0: _hashStateZ = 0x8767 ; // (int)(3579807591LL & 0xffff) ; aoqi@0: _hashStateW = 273326509 ; aoqi@0: aoqi@0: _OnTrap = 0 ; aoqi@0: _schedctl = NULL ; aoqi@0: _Stalled = 0 ; aoqi@0: _TypeTag = 0x2BAD ; aoqi@0: aoqi@0: // Many of the following fields are effectively final - immutable aoqi@0: // Note that nascent threads can't use the Native Monitor-Mutex aoqi@0: // construct until the _MutexEvent is initialized ... aoqi@0: // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents aoqi@0: // we might instead use a stack of ParkEvents that we could provision on-demand. aoqi@0: // The stack would act as a cache to avoid calls to ParkEvent::Allocate() aoqi@0: // and ::Release() aoqi@0: _ParkEvent = ParkEvent::Allocate (this) ; aoqi@0: _SleepEvent = ParkEvent::Allocate (this) ; aoqi@0: _MutexEvent = ParkEvent::Allocate (this) ; aoqi@0: _MuxEvent = ParkEvent::Allocate (this) ; aoqi@0: aoqi@0: #ifdef CHECK_UNHANDLED_OOPS aoqi@0: if (CheckUnhandledOops) { aoqi@0: _unhandled_oops = new UnhandledOops(this); aoqi@0: } aoqi@0: #endif // CHECK_UNHANDLED_OOPS aoqi@0: #ifdef ASSERT aoqi@0: if (UseBiasedLocking) { aoqi@0: assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed"); aoqi@0: assert(this == _real_malloc_address || aoqi@0: this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment), aoqi@0: "bug in forced alignment of thread objects"); aoqi@0: } aoqi@0: #endif /* ASSERT */ aoqi@0: } aoqi@0: aoqi@0: void Thread::initialize_thread_local_storage() { aoqi@0: // Note: Make sure this method only calls aoqi@0: // non-blocking operations. Otherwise, it might not work aoqi@0: // with the thread-startup/safepoint interaction. aoqi@0: aoqi@0: // During Java thread startup, safepoint code should allow this aoqi@0: // method to complete because it may need to allocate memory to aoqi@0: // store information for the new thread. aoqi@0: aoqi@0: // initialize structure dependent on thread local storage aoqi@0: ThreadLocalStorage::set_thread(this); aoqi@0: } aoqi@0: aoqi@0: void Thread::record_stack_base_and_size() { aoqi@0: set_stack_base(os::current_stack_base()); aoqi@0: set_stack_size(os::current_stack_size()); aoqi@0: if (is_Java_thread()) { aoqi@0: ((JavaThread*) this)->set_stack_overflow_limit(); aoqi@0: } aoqi@0: // CR 7190089: on Solaris, primordial thread's stack is adjusted aoqi@0: // in initialize_thread(). Without the adjustment, stack size is aoqi@0: // incorrect if stack is set to unlimited (ulimit -s unlimited). aoqi@0: // So far, only Solaris has real implementation of initialize_thread(). aoqi@0: // aoqi@0: // set up any platform-specific state. aoqi@0: os::initialize_thread(this); aoqi@0: aoqi@0: #if INCLUDE_NMT aoqi@0: // record thread's native stack, stack grows downward aoqi@0: address stack_low_addr = stack_base() - stack_size(); aoqi@0: MemTracker::record_thread_stack(stack_low_addr, stack_size(), this, aoqi@0: CURRENT_PC); aoqi@0: #endif // INCLUDE_NMT aoqi@0: } aoqi@0: aoqi@0: aoqi@0: Thread::~Thread() { aoqi@0: // Reclaim the objectmonitors from the omFreeList of the moribund thread. aoqi@0: ObjectSynchronizer::omFlush (this) ; aoqi@0: aoqi@0: EVENT_THREAD_DESTRUCT(this); aoqi@0: aoqi@0: // stack_base can be NULL if the thread is never started or exited before aoqi@0: // record_stack_base_and_size called. Although, we would like to ensure aoqi@0: // that all started threads do call record_stack_base_and_size(), there is aoqi@0: // not proper way to enforce that. aoqi@0: #if INCLUDE_NMT aoqi@0: if (_stack_base != NULL) { aoqi@0: address low_stack_addr = stack_base() - stack_size(); aoqi@0: MemTracker::release_thread_stack(low_stack_addr, stack_size(), this); aoqi@0: #ifdef ASSERT aoqi@0: set_stack_base(NULL); aoqi@0: #endif aoqi@0: } aoqi@0: #endif // INCLUDE_NMT aoqi@0: aoqi@0: // deallocate data structures aoqi@0: delete resource_area(); aoqi@0: // since the handle marks are using the handle area, we have to deallocated the root aoqi@0: // handle mark before deallocating the thread's handle area, aoqi@0: assert(last_handle_mark() != NULL, "check we have an element"); aoqi@0: delete last_handle_mark(); aoqi@0: assert(last_handle_mark() == NULL, "check we have reached the end"); aoqi@0: aoqi@0: // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads. aoqi@0: // We NULL out the fields for good hygiene. aoqi@0: ParkEvent::Release (_ParkEvent) ; _ParkEvent = NULL ; aoqi@0: ParkEvent::Release (_SleepEvent) ; _SleepEvent = NULL ; aoqi@0: ParkEvent::Release (_MutexEvent) ; _MutexEvent = NULL ; aoqi@0: ParkEvent::Release (_MuxEvent) ; _MuxEvent = NULL ; aoqi@0: aoqi@0: delete handle_area(); aoqi@0: delete metadata_handles(); aoqi@0: aoqi@0: // osthread() can be NULL, if creation of thread failed. aoqi@0: if (osthread() != NULL) os::free_thread(osthread()); aoqi@0: aoqi@0: delete _SR_lock; aoqi@0: aoqi@0: // clear thread local storage if the Thread is deleting itself aoqi@0: if (this == Thread::current()) { aoqi@0: ThreadLocalStorage::set_thread(NULL); aoqi@0: } else { aoqi@0: // In the case where we're not the current thread, invalidate all the aoqi@0: // caches in case some code tries to get the current thread or the aoqi@0: // thread that was destroyed, and gets stale information. aoqi@0: ThreadLocalStorage::invalidate_all(); aoqi@0: } aoqi@0: CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();) aoqi@0: } aoqi@0: aoqi@0: // NOTE: dummy function for assertion purpose. aoqi@0: void Thread::run() { aoqi@0: ShouldNotReachHere(); aoqi@0: } aoqi@0: aoqi@0: #ifdef ASSERT aoqi@0: // Private method to check for dangling thread pointer aoqi@0: void check_for_dangling_thread_pointer(Thread *thread) { aoqi@0: assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(), aoqi@0: "possibility of dangling Thread pointer"); aoqi@0: } aoqi@0: #endif aoqi@0: aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: // Tracing method for basic thread operations aoqi@0: void Thread::trace(const char* msg, const Thread* const thread) { aoqi@0: if (!TraceThreadEvents) return; aoqi@0: ResourceMark rm; aoqi@0: ThreadCritical tc; aoqi@0: const char *name = "non-Java thread"; aoqi@0: int prio = -1; aoqi@0: if (thread->is_Java_thread() aoqi@0: && !thread->is_Compiler_thread()) { aoqi@0: // The Threads_lock must be held to get information about aoqi@0: // this thread but may not be in some situations when aoqi@0: // tracing thread events. aoqi@0: bool release_Threads_lock = false; aoqi@0: if (!Threads_lock->owned_by_self()) { aoqi@0: Threads_lock->lock(); aoqi@0: release_Threads_lock = true; aoqi@0: } aoqi@0: JavaThread* jt = (JavaThread *)thread; aoqi@0: name = (char *)jt->get_thread_name(); aoqi@0: oop thread_oop = jt->threadObj(); aoqi@0: if (thread_oop != NULL) { aoqi@0: prio = java_lang_Thread::priority(thread_oop); aoqi@0: } aoqi@0: if (release_Threads_lock) { aoqi@0: Threads_lock->unlock(); aoqi@0: } aoqi@0: } aoqi@0: tty->print_cr("Thread::%s " INTPTR_FORMAT " [%lx] %s (prio: %d)", msg, thread, thread->osthread()->thread_id(), name, prio); aoqi@0: } aoqi@0: #endif aoqi@0: aoqi@0: aoqi@0: ThreadPriority Thread::get_priority(const Thread* const thread) { aoqi@0: trace("get priority", thread); aoqi@0: ThreadPriority priority; aoqi@0: // Can return an error! aoqi@0: (void)os::get_priority(thread, priority); aoqi@0: assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found"); aoqi@0: return priority; aoqi@0: } aoqi@0: aoqi@0: void Thread::set_priority(Thread* thread, ThreadPriority priority) { aoqi@0: trace("set priority", thread); aoqi@0: debug_only(check_for_dangling_thread_pointer(thread);) aoqi@0: // Can return an error! aoqi@0: (void)os::set_priority(thread, priority); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void Thread::start(Thread* thread) { aoqi@0: trace("start", thread); aoqi@0: // Start is different from resume in that its safety is guaranteed by context or aoqi@0: // being called from a Java method synchronized on the Thread object. aoqi@0: if (!DisableStartThread) { aoqi@0: if (thread->is_Java_thread()) { aoqi@0: // Initialize the thread state to RUNNABLE before starting this thread. aoqi@0: // Can not set it after the thread started because we do not know the aoqi@0: // exact thread state at that time. It could be in MONITOR_WAIT or aoqi@0: // in SLEEPING or some other state. aoqi@0: java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(), aoqi@0: java_lang_Thread::RUNNABLE); aoqi@0: } aoqi@0: os::start_thread(thread); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Enqueue a VM_Operation to do the job for us - sometime later aoqi@0: void Thread::send_async_exception(oop java_thread, oop java_throwable) { aoqi@0: VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable); aoqi@0: VMThread::execute(vm_stop); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // aoqi@0: // Check if an external suspend request has completed (or has been aoqi@0: // cancelled). Returns true if the thread is externally suspended and aoqi@0: // false otherwise. aoqi@0: // aoqi@0: // The bits parameter returns information about the code path through aoqi@0: // the routine. Useful for debugging: aoqi@0: // aoqi@0: // set in is_ext_suspend_completed(): aoqi@0: // 0x00000001 - routine was entered aoqi@0: // 0x00000010 - routine return false at end aoqi@0: // 0x00000100 - thread exited (return false) aoqi@0: // 0x00000200 - suspend request cancelled (return false) aoqi@0: // 0x00000400 - thread suspended (return true) aoqi@0: // 0x00001000 - thread is in a suspend equivalent state (return true) aoqi@0: // 0x00002000 - thread is native and walkable (return true) aoqi@0: // 0x00004000 - thread is native_trans and walkable (needed retry) aoqi@0: // aoqi@0: // set in wait_for_ext_suspend_completion(): aoqi@0: // 0x00010000 - routine was entered aoqi@0: // 0x00020000 - suspend request cancelled before loop (return false) aoqi@0: // 0x00040000 - thread suspended before loop (return true) aoqi@0: // 0x00080000 - suspend request cancelled in loop (return false) aoqi@0: // 0x00100000 - thread suspended in loop (return true) aoqi@0: // 0x00200000 - suspend not completed during retry loop (return false) aoqi@0: // aoqi@0: aoqi@0: // Helper class for tracing suspend wait debug bits. aoqi@0: // aoqi@0: // 0x00000100 indicates that the target thread exited before it could aoqi@0: // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and aoqi@0: // 0x00080000 each indicate a cancelled suspend request so they don't aoqi@0: // count as wait failures either. aoqi@0: #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000) aoqi@0: aoqi@0: class TraceSuspendDebugBits : public StackObj { aoqi@0: private: aoqi@0: JavaThread * jt; aoqi@0: bool is_wait; aoqi@0: bool called_by_wait; // meaningful when !is_wait aoqi@0: uint32_t * bits; aoqi@0: aoqi@0: public: aoqi@0: TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait, aoqi@0: uint32_t *_bits) { aoqi@0: jt = _jt; aoqi@0: is_wait = _is_wait; aoqi@0: called_by_wait = _called_by_wait; aoqi@0: bits = _bits; aoqi@0: } aoqi@0: aoqi@0: ~TraceSuspendDebugBits() { aoqi@0: if (!is_wait) { aoqi@0: #if 1 aoqi@0: // By default, don't trace bits for is_ext_suspend_completed() calls. aoqi@0: // That trace is very chatty. aoqi@0: return; aoqi@0: #else aoqi@0: if (!called_by_wait) { aoqi@0: // If tracing for is_ext_suspend_completed() is enabled, then only aoqi@0: // trace calls to it from wait_for_ext_suspend_completion() aoqi@0: return; aoqi@0: } aoqi@0: #endif aoqi@0: } aoqi@0: aoqi@0: if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) { aoqi@0: if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) { aoqi@0: MutexLocker ml(Threads_lock); // needed for get_thread_name() aoqi@0: ResourceMark rm; aoqi@0: aoqi@0: tty->print_cr( aoqi@0: "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)", aoqi@0: jt->get_thread_name(), *bits); aoqi@0: aoqi@0: guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed"); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: }; aoqi@0: #undef DEBUG_FALSE_BITS aoqi@0: aoqi@0: aoqi@0: bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits) { aoqi@0: TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits); aoqi@0: aoqi@0: bool did_trans_retry = false; // only do thread_in_native_trans retry once aoqi@0: bool do_trans_retry; // flag to force the retry aoqi@0: aoqi@0: *bits |= 0x00000001; aoqi@0: aoqi@0: do { aoqi@0: do_trans_retry = false; aoqi@0: aoqi@0: if (is_exiting()) { aoqi@0: // Thread is in the process of exiting. This is always checked aoqi@0: // first to reduce the risk of dereferencing a freed JavaThread. aoqi@0: *bits |= 0x00000100; aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: if (!is_external_suspend()) { aoqi@0: // Suspend request is cancelled. This is always checked before aoqi@0: // is_ext_suspended() to reduce the risk of a rogue resume aoqi@0: // confusing the thread that made the suspend request. aoqi@0: *bits |= 0x00000200; aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: if (is_ext_suspended()) { aoqi@0: // thread is suspended aoqi@0: *bits |= 0x00000400; aoqi@0: return true; aoqi@0: } aoqi@0: aoqi@0: // Now that we no longer do hard suspends of threads running aoqi@0: // native code, the target thread can be changing thread state aoqi@0: // while we are in this routine: aoqi@0: // aoqi@0: // _thread_in_native -> _thread_in_native_trans -> _thread_blocked aoqi@0: // aoqi@0: // We save a copy of the thread state as observed at this moment aoqi@0: // and make our decision about suspend completeness based on the aoqi@0: // copy. This closes the race where the thread state is seen as aoqi@0: // _thread_in_native_trans in the if-thread_blocked check, but is aoqi@0: // seen as _thread_blocked in if-thread_in_native_trans check. aoqi@0: JavaThreadState save_state = thread_state(); aoqi@0: aoqi@0: if (save_state == _thread_blocked && is_suspend_equivalent()) { aoqi@0: // If the thread's state is _thread_blocked and this blocking aoqi@0: // condition is known to be equivalent to a suspend, then we can aoqi@0: // consider the thread to be externally suspended. This means that aoqi@0: // the code that sets _thread_blocked has been modified to do aoqi@0: // self-suspension if the blocking condition releases. We also aoqi@0: // used to check for CONDVAR_WAIT here, but that is now covered by aoqi@0: // the _thread_blocked with self-suspension check. aoqi@0: // aoqi@0: // Return true since we wouldn't be here unless there was still an aoqi@0: // external suspend request. aoqi@0: *bits |= 0x00001000; aoqi@0: return true; aoqi@0: } else if (save_state == _thread_in_native && frame_anchor()->walkable()) { aoqi@0: // Threads running native code will self-suspend on native==>VM/Java aoqi@0: // transitions. If its stack is walkable (should always be the case aoqi@0: // unless this function is called before the actual java_suspend() aoqi@0: // call), then the wait is done. aoqi@0: *bits |= 0x00002000; aoqi@0: return true; aoqi@0: } else if (!called_by_wait && !did_trans_retry && aoqi@0: save_state == _thread_in_native_trans && aoqi@0: frame_anchor()->walkable()) { aoqi@0: // The thread is transitioning from thread_in_native to another aoqi@0: // thread state. check_safepoint_and_suspend_for_native_trans() aoqi@0: // will force the thread to self-suspend. If it hasn't gotten aoqi@0: // there yet we may have caught the thread in-between the native aoqi@0: // code check above and the self-suspend. Lucky us. If we were aoqi@0: // called by wait_for_ext_suspend_completion(), then it aoqi@0: // will be doing the retries so we don't have to. aoqi@0: // aoqi@0: // Since we use the saved thread state in the if-statement above, aoqi@0: // there is a chance that the thread has already transitioned to aoqi@0: // _thread_blocked by the time we get here. In that case, we will aoqi@0: // make a single unnecessary pass through the logic below. This aoqi@0: // doesn't hurt anything since we still do the trans retry. aoqi@0: aoqi@0: *bits |= 0x00004000; aoqi@0: aoqi@0: // Once the thread leaves thread_in_native_trans for another aoqi@0: // thread state, we break out of this retry loop. We shouldn't aoqi@0: // need this flag to prevent us from getting back here, but aoqi@0: // sometimes paranoia is good. aoqi@0: did_trans_retry = true; aoqi@0: aoqi@0: // We wait for the thread to transition to a more usable state. aoqi@0: for (int i = 1; i <= SuspendRetryCount; i++) { aoqi@0: // We used to do an "os::yield_all(i)" call here with the intention aoqi@0: // that yielding would increase on each retry. However, the parameter aoqi@0: // is ignored on Linux which means the yield didn't scale up. Waiting aoqi@0: // on the SR_lock below provides a much more predictable scale up for aoqi@0: // the delay. It also provides a simple/direct point to check for any aoqi@0: // safepoint requests from the VMThread aoqi@0: aoqi@0: // temporarily drops SR_lock while doing wait with safepoint check aoqi@0: // (if we're a JavaThread - the WatcherThread can also call this) aoqi@0: // and increase delay with each retry aoqi@0: SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay); aoqi@0: aoqi@0: // check the actual thread state instead of what we saved above aoqi@0: if (thread_state() != _thread_in_native_trans) { aoqi@0: // the thread has transitioned to another thread state so aoqi@0: // try all the checks (except this one) one more time. aoqi@0: do_trans_retry = true; aoqi@0: break; aoqi@0: } aoqi@0: } // end retry loop aoqi@0: aoqi@0: aoqi@0: } aoqi@0: } while (do_trans_retry); aoqi@0: aoqi@0: *bits |= 0x00000010; aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: // aoqi@0: // Wait for an external suspend request to complete (or be cancelled). aoqi@0: // Returns true if the thread is externally suspended and false otherwise. aoqi@0: // aoqi@0: bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay, aoqi@0: uint32_t *bits) { aoqi@0: TraceSuspendDebugBits tsdb(this, true /* is_wait */, aoqi@0: false /* !called_by_wait */, bits); aoqi@0: aoqi@0: // local flag copies to minimize SR_lock hold time aoqi@0: bool is_suspended; aoqi@0: bool pending; aoqi@0: uint32_t reset_bits; aoqi@0: aoqi@0: // set a marker so is_ext_suspend_completed() knows we are the caller aoqi@0: *bits |= 0x00010000; aoqi@0: aoqi@0: // We use reset_bits to reinitialize the bits value at the top of aoqi@0: // each retry loop. This allows the caller to make use of any aoqi@0: // unused bits for their own marking purposes. aoqi@0: reset_bits = *bits; aoqi@0: aoqi@0: { aoqi@0: MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); aoqi@0: is_suspended = is_ext_suspend_completed(true /* called_by_wait */, aoqi@0: delay, bits); aoqi@0: pending = is_external_suspend(); aoqi@0: } aoqi@0: // must release SR_lock to allow suspension to complete aoqi@0: aoqi@0: if (!pending) { aoqi@0: // A cancelled suspend request is the only false return from aoqi@0: // is_ext_suspend_completed() that keeps us from entering the aoqi@0: // retry loop. aoqi@0: *bits |= 0x00020000; aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: if (is_suspended) { aoqi@0: *bits |= 0x00040000; aoqi@0: return true; aoqi@0: } aoqi@0: aoqi@0: for (int i = 1; i <= retries; i++) { aoqi@0: *bits = reset_bits; // reinit to only track last retry aoqi@0: aoqi@0: // We used to do an "os::yield_all(i)" call here with the intention aoqi@0: // that yielding would increase on each retry. However, the parameter aoqi@0: // is ignored on Linux which means the yield didn't scale up. Waiting aoqi@0: // on the SR_lock below provides a much more predictable scale up for aoqi@0: // the delay. It also provides a simple/direct point to check for any aoqi@0: // safepoint requests from the VMThread aoqi@0: aoqi@0: { aoqi@0: MutexLocker ml(SR_lock()); aoqi@0: // wait with safepoint check (if we're a JavaThread - the WatcherThread aoqi@0: // can also call this) and increase delay with each retry aoqi@0: SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay); aoqi@0: aoqi@0: is_suspended = is_ext_suspend_completed(true /* called_by_wait */, aoqi@0: delay, bits); aoqi@0: aoqi@0: // It is possible for the external suspend request to be cancelled aoqi@0: // (by a resume) before the actual suspend operation is completed. aoqi@0: // Refresh our local copy to see if we still need to wait. aoqi@0: pending = is_external_suspend(); aoqi@0: } aoqi@0: aoqi@0: if (!pending) { aoqi@0: // A cancelled suspend request is the only false return from aoqi@0: // is_ext_suspend_completed() that keeps us from staying in the aoqi@0: // retry loop. aoqi@0: *bits |= 0x00080000; aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: if (is_suspended) { aoqi@0: *bits |= 0x00100000; aoqi@0: return true; aoqi@0: } aoqi@0: } // end retry loop aoqi@0: aoqi@0: // thread did not suspend after all our retries aoqi@0: *bits |= 0x00200000; aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: void JavaThread::record_jump(address target, address instr, const char* file, int line) { aoqi@0: aoqi@0: // This should not need to be atomic as the only way for simultaneous aoqi@0: // updates is via interrupts. Even then this should be rare or non-existant aoqi@0: // and we don't care that much anyway. aoqi@0: aoqi@0: int index = _jmp_ring_index; aoqi@0: _jmp_ring_index = (index + 1 ) & (jump_ring_buffer_size - 1); aoqi@0: _jmp_ring[index]._target = (intptr_t) target; aoqi@0: _jmp_ring[index]._instruction = (intptr_t) instr; aoqi@0: _jmp_ring[index]._file = file; aoqi@0: _jmp_ring[index]._line = line; aoqi@0: } aoqi@0: #endif /* PRODUCT */ aoqi@0: aoqi@0: // Called by flat profiler aoqi@0: // Callers have already called wait_for_ext_suspend_completion aoqi@0: // The assertion for that is currently too complex to put here: aoqi@0: bool JavaThread::profile_last_Java_frame(frame* _fr) { aoqi@0: bool gotframe = false; aoqi@0: // self suspension saves needed state. aoqi@0: if (has_last_Java_frame() && _anchor.walkable()) { aoqi@0: *_fr = pd_last_frame(); aoqi@0: gotframe = true; aoqi@0: } aoqi@0: return gotframe; aoqi@0: } aoqi@0: aoqi@0: void Thread::interrupt(Thread* thread) { aoqi@0: trace("interrupt", thread); aoqi@0: debug_only(check_for_dangling_thread_pointer(thread);) aoqi@0: os::interrupt(thread); aoqi@0: } aoqi@0: aoqi@0: bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) { aoqi@0: trace("is_interrupted", thread); aoqi@0: debug_only(check_for_dangling_thread_pointer(thread);) aoqi@0: // Note: If clear_interrupted==false, this simply fetches and aoqi@0: // returns the value of the field osthread()->interrupted(). aoqi@0: return os::is_interrupted(thread, clear_interrupted); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // GC Support aoqi@0: bool Thread::claim_oops_do_par_case(int strong_roots_parity) { aoqi@0: jint thread_parity = _oops_do_parity; aoqi@0: if (thread_parity != strong_roots_parity) { aoqi@0: jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity); aoqi@0: if (res == thread_parity) { aoqi@0: return true; aoqi@0: } else { aoqi@0: guarantee(res == strong_roots_parity, "Or else what?"); aoqi@0: assert(SharedHeap::heap()->workers()->active_workers() > 0, aoqi@0: "Should only fail when parallel."); aoqi@0: return false; aoqi@0: } aoqi@0: } aoqi@0: assert(SharedHeap::heap()->workers()->active_workers() > 0, aoqi@0: "Should only fail when parallel."); aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: void Thread::oops_do(OopClosure* f, CLDToOopClosure* cld_f, CodeBlobClosure* cf) { aoqi@0: active_handles()->oops_do(f); aoqi@0: // Do oop for ThreadShadow aoqi@0: f->do_oop((oop*)&_pending_exception); aoqi@0: handle_area()->oops_do(f); aoqi@0: } aoqi@0: aoqi@0: void Thread::nmethods_do(CodeBlobClosure* cf) { aoqi@0: // no nmethods in a generic thread... aoqi@0: } aoqi@0: aoqi@0: void Thread::metadata_do(void f(Metadata*)) { aoqi@0: if (metadata_handles() != NULL) { aoqi@0: for (int i = 0; i< metadata_handles()->length(); i++) { aoqi@0: f(metadata_handles()->at(i)); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void Thread::print_on(outputStream* st) const { aoqi@0: // get_priority assumes osthread initialized aoqi@0: if (osthread() != NULL) { aoqi@0: int os_prio; aoqi@0: if (os::get_native_priority(this, &os_prio) == OS_OK) { aoqi@0: st->print("os_prio=%d ", os_prio); aoqi@0: } aoqi@0: st->print("tid=" INTPTR_FORMAT " ", this); aoqi@0: osthread()->print_on(st); aoqi@0: } aoqi@0: debug_only(if (WizardMode) print_owned_locks_on(st);) aoqi@0: } aoqi@0: aoqi@0: // Thread::print_on_error() is called by fatal error handler. Don't use aoqi@0: // any lock or allocate memory. aoqi@0: void Thread::print_on_error(outputStream* st, char* buf, int buflen) const { aoqi@0: if (is_VM_thread()) st->print("VMThread"); aoqi@0: else if (is_Compiler_thread()) st->print("CompilerThread"); aoqi@0: else if (is_Java_thread()) st->print("JavaThread"); aoqi@0: else if (is_GC_task_thread()) st->print("GCTaskThread"); aoqi@0: else if (is_Watcher_thread()) st->print("WatcherThread"); aoqi@0: else if (is_ConcurrentGC_thread()) st->print("ConcurrentGCThread"); aoqi@0: else st->print("Thread"); aoqi@0: aoqi@0: st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]", aoqi@0: _stack_base - _stack_size, _stack_base); aoqi@0: aoqi@0: if (osthread()) { aoqi@0: st->print(" [id=%d]", osthread()->thread_id()); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: #ifdef ASSERT aoqi@0: void Thread::print_owned_locks_on(outputStream* st) const { aoqi@0: Monitor *cur = _owned_locks; aoqi@0: if (cur == NULL) { aoqi@0: st->print(" (no locks) "); aoqi@0: } else { aoqi@0: st->print_cr(" Locks owned:"); aoqi@0: while(cur) { aoqi@0: cur->print_on(st); aoqi@0: cur = cur->next(); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: static int ref_use_count = 0; aoqi@0: aoqi@0: bool Thread::owns_locks_but_compiled_lock() const { aoqi@0: for(Monitor *cur = _owned_locks; cur; cur = cur->next()) { aoqi@0: if (cur != Compile_lock) return true; aoqi@0: } aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: #endif aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: aoqi@0: // The flag: potential_vm_operation notifies if this particular safepoint state could potential aoqi@0: // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that aoqi@0: // no threads which allow_vm_block's are held aoqi@0: void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) { aoqi@0: // Check if current thread is allowed to block at a safepoint aoqi@0: if (!(_allow_safepoint_count == 0)) aoqi@0: fatal("Possible safepoint reached by thread that does not allow it"); aoqi@0: if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) { aoqi@0: fatal("LEAF method calling lock?"); aoqi@0: } aoqi@0: aoqi@0: #ifdef ASSERT aoqi@0: if (potential_vm_operation && is_Java_thread() aoqi@0: && !Universe::is_bootstrapping()) { aoqi@0: // Make sure we do not hold any locks that the VM thread also uses. aoqi@0: // This could potentially lead to deadlocks aoqi@0: for(Monitor *cur = _owned_locks; cur; cur = cur->next()) { aoqi@0: // Threads_lock is special, since the safepoint synchronization will not start before this is aoqi@0: // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock, aoqi@0: // since it is used to transfer control between JavaThreads and the VMThread aoqi@0: // Do not *exclude* any locks unless you are absolutly sure it is correct. Ask someone else first! aoqi@0: if ( (cur->allow_vm_block() && aoqi@0: cur != Threads_lock && aoqi@0: cur != Compile_lock && // Temporary: should not be necessary when we get spearate compilation aoqi@0: cur != VMOperationRequest_lock && aoqi@0: cur != VMOperationQueue_lock) || aoqi@0: cur->rank() == Mutex::special) { aoqi@0: warning("Thread holding lock at safepoint that vm can block on: %s", cur->name()); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (GCALotAtAllSafepoints) { aoqi@0: // We could enter a safepoint here and thus have a gc aoqi@0: InterfaceSupport::check_gc_alot(); aoqi@0: } aoqi@0: #endif aoqi@0: } aoqi@0: #endif aoqi@0: aoqi@0: bool Thread::is_in_stack(address adr) const { aoqi@0: assert(Thread::current() == this, "is_in_stack can only be called from current thread"); aoqi@0: address end = os::current_stack_pointer(); aoqi@0: // Allow non Java threads to call this without stack_base aoqi@0: if (_stack_base == NULL) return true; aoqi@0: if (stack_base() >= adr && adr >= end) return true; aoqi@0: aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: bool Thread::is_in_usable_stack(address adr) const { aoqi@0: size_t stack_guard_size = os::uses_stack_guard_pages() ? (StackYellowPages + StackRedPages) * os::vm_page_size() : 0; aoqi@0: size_t usable_stack_size = _stack_size - stack_guard_size; aoqi@0: aoqi@0: return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size)); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter aoqi@0: // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being aoqi@0: // used for compilation in the future. If that change is made, the need for these methods aoqi@0: // should be revisited, and they should be removed if possible. aoqi@0: aoqi@0: bool Thread::is_lock_owned(address adr) const { aoqi@0: return on_local_stack(adr); aoqi@0: } aoqi@0: aoqi@0: bool Thread::set_as_starting_thread() { aoqi@0: // NOTE: this must be called inside the main thread. aoqi@0: return os::create_main_thread((JavaThread*)this); aoqi@0: } aoqi@0: aoqi@0: static void initialize_class(Symbol* class_name, TRAPS) { aoqi@0: Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK); aoqi@0: InstanceKlass::cast(klass)->initialize(CHECK); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // Creates the initial ThreadGroup aoqi@0: static Handle create_initial_thread_group(TRAPS) { aoqi@0: Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ThreadGroup(), true, CHECK_NH); aoqi@0: instanceKlassHandle klass (THREAD, k); aoqi@0: aoqi@0: Handle system_instance = klass->allocate_instance_handle(CHECK_NH); aoqi@0: { aoqi@0: JavaValue result(T_VOID); aoqi@0: JavaCalls::call_special(&result, aoqi@0: system_instance, aoqi@0: klass, aoqi@0: vmSymbols::object_initializer_name(), aoqi@0: vmSymbols::void_method_signature(), aoqi@0: CHECK_NH); aoqi@0: } aoqi@0: Universe::set_system_thread_group(system_instance()); aoqi@0: aoqi@0: Handle main_instance = klass->allocate_instance_handle(CHECK_NH); aoqi@0: { aoqi@0: JavaValue result(T_VOID); aoqi@0: Handle string = java_lang_String::create_from_str("main", CHECK_NH); aoqi@0: JavaCalls::call_special(&result, aoqi@0: main_instance, aoqi@0: klass, aoqi@0: vmSymbols::object_initializer_name(), aoqi@0: vmSymbols::threadgroup_string_void_signature(), aoqi@0: system_instance, aoqi@0: string, aoqi@0: CHECK_NH); aoqi@0: } aoqi@0: return main_instance; aoqi@0: } aoqi@0: aoqi@0: // Creates the initial Thread aoqi@0: static oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) { aoqi@0: Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_NULL); aoqi@0: instanceKlassHandle klass (THREAD, k); aoqi@0: instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL); aoqi@0: aoqi@0: java_lang_Thread::set_thread(thread_oop(), thread); aoqi@0: java_lang_Thread::set_priority(thread_oop(), NormPriority); aoqi@0: thread->set_threadObj(thread_oop()); aoqi@0: aoqi@0: Handle string = java_lang_String::create_from_str("main", CHECK_NULL); aoqi@0: aoqi@0: JavaValue result(T_VOID); aoqi@0: JavaCalls::call_special(&result, thread_oop, aoqi@0: klass, aoqi@0: vmSymbols::object_initializer_name(), aoqi@0: vmSymbols::threadgroup_string_void_signature(), aoqi@0: thread_group, aoqi@0: string, aoqi@0: CHECK_NULL); aoqi@0: return thread_oop(); aoqi@0: } aoqi@0: aoqi@0: static void call_initializeSystemClass(TRAPS) { aoqi@0: Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); aoqi@0: instanceKlassHandle klass (THREAD, k); aoqi@0: aoqi@0: JavaValue result(T_VOID); aoqi@0: JavaCalls::call_static(&result, klass, vmSymbols::initializeSystemClass_name(), aoqi@0: vmSymbols::void_method_signature(), CHECK); aoqi@0: } aoqi@0: aoqi@0: char java_runtime_name[128] = ""; aoqi@0: char java_runtime_version[128] = ""; aoqi@0: aoqi@0: // extract the JRE name from sun.misc.Version.java_runtime_name aoqi@0: static const char* get_java_runtime_name(TRAPS) { aoqi@0: Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(), aoqi@0: Handle(), Handle(), CHECK_AND_CLEAR_NULL); aoqi@0: fieldDescriptor fd; aoqi@0: bool found = k != NULL && aoqi@0: InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(), aoqi@0: vmSymbols::string_signature(), &fd); aoqi@0: if (found) { aoqi@0: oop name_oop = k->java_mirror()->obj_field(fd.offset()); aoqi@0: if (name_oop == NULL) aoqi@0: return NULL; aoqi@0: const char* name = java_lang_String::as_utf8_string(name_oop, aoqi@0: java_runtime_name, aoqi@0: sizeof(java_runtime_name)); aoqi@0: return name; aoqi@0: } else { aoqi@0: return NULL; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // extract the JRE version from sun.misc.Version.java_runtime_version aoqi@0: static const char* get_java_runtime_version(TRAPS) { aoqi@0: Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(), aoqi@0: Handle(), Handle(), CHECK_AND_CLEAR_NULL); aoqi@0: fieldDescriptor fd; aoqi@0: bool found = k != NULL && aoqi@0: InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(), aoqi@0: vmSymbols::string_signature(), &fd); aoqi@0: if (found) { aoqi@0: oop name_oop = k->java_mirror()->obj_field(fd.offset()); aoqi@0: if (name_oop == NULL) aoqi@0: return NULL; aoqi@0: const char* name = java_lang_String::as_utf8_string(name_oop, aoqi@0: java_runtime_version, aoqi@0: sizeof(java_runtime_version)); aoqi@0: return name; aoqi@0: } else { aoqi@0: return NULL; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // General purpose hook into Java code, run once when the VM is initialized. aoqi@0: // The Java library method itself may be changed independently from the VM. aoqi@0: static void call_postVMInitHook(TRAPS) { aoqi@0: Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_PostVMInitHook(), THREAD); aoqi@0: instanceKlassHandle klass (THREAD, k); aoqi@0: if (klass.not_null()) { aoqi@0: JavaValue result(T_VOID); aoqi@0: JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(), aoqi@0: vmSymbols::void_method_signature(), aoqi@0: CHECK); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: static void reset_vm_info_property(TRAPS) { aoqi@0: // the vm info string aoqi@0: ResourceMark rm(THREAD); aoqi@0: const char *vm_info = VM_Version::vm_info_string(); aoqi@0: aoqi@0: // java.lang.System class aoqi@0: Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); aoqi@0: instanceKlassHandle klass (THREAD, k); aoqi@0: aoqi@0: // setProperty arguments aoqi@0: Handle key_str = java_lang_String::create_from_str("java.vm.info", CHECK); aoqi@0: Handle value_str = java_lang_String::create_from_str(vm_info, CHECK); aoqi@0: aoqi@0: // return value aoqi@0: JavaValue r(T_OBJECT); aoqi@0: aoqi@0: // public static String setProperty(String key, String value); aoqi@0: JavaCalls::call_static(&r, aoqi@0: klass, aoqi@0: vmSymbols::setProperty_name(), aoqi@0: vmSymbols::string_string_string_signature(), aoqi@0: key_str, aoqi@0: value_str, aoqi@0: CHECK); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void JavaThread::allocate_threadObj(Handle thread_group, char* thread_name, bool daemon, TRAPS) { aoqi@0: assert(thread_group.not_null(), "thread group should be specified"); aoqi@0: assert(threadObj() == NULL, "should only create Java thread object once"); aoqi@0: aoqi@0: Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK); aoqi@0: instanceKlassHandle klass (THREAD, k); aoqi@0: instanceHandle thread_oop = klass->allocate_instance_handle(CHECK); aoqi@0: aoqi@0: java_lang_Thread::set_thread(thread_oop(), this); aoqi@0: java_lang_Thread::set_priority(thread_oop(), NormPriority); aoqi@0: set_threadObj(thread_oop()); aoqi@0: aoqi@0: JavaValue result(T_VOID); aoqi@0: if (thread_name != NULL) { aoqi@0: Handle name = java_lang_String::create_from_str(thread_name, CHECK); aoqi@0: // Thread gets assigned specified name and null target aoqi@0: JavaCalls::call_special(&result, aoqi@0: thread_oop, aoqi@0: klass, aoqi@0: vmSymbols::object_initializer_name(), aoqi@0: vmSymbols::threadgroup_string_void_signature(), aoqi@0: thread_group, // Argument 1 aoqi@0: name, // Argument 2 aoqi@0: THREAD); aoqi@0: } else { aoqi@0: // Thread gets assigned name "Thread-nnn" and null target aoqi@0: // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument) aoqi@0: JavaCalls::call_special(&result, aoqi@0: thread_oop, aoqi@0: klass, aoqi@0: vmSymbols::object_initializer_name(), aoqi@0: vmSymbols::threadgroup_runnable_void_signature(), aoqi@0: thread_group, // Argument 1 aoqi@0: Handle(), // Argument 2 aoqi@0: THREAD); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: if (daemon) { aoqi@0: java_lang_Thread::set_daemon(thread_oop()); aoqi@0: } aoqi@0: aoqi@0: if (HAS_PENDING_EXCEPTION) { aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: KlassHandle group(this, SystemDictionary::ThreadGroup_klass()); aoqi@0: Handle threadObj(this, this->threadObj()); aoqi@0: aoqi@0: JavaCalls::call_special(&result, aoqi@0: thread_group, aoqi@0: group, aoqi@0: vmSymbols::add_method_name(), aoqi@0: vmSymbols::thread_void_signature(), aoqi@0: threadObj, // Arg 1 aoqi@0: THREAD); aoqi@0: aoqi@0: aoqi@0: } aoqi@0: aoqi@0: // NamedThread -- non-JavaThread subclasses with multiple aoqi@0: // uniquely named instances should derive from this. aoqi@0: NamedThread::NamedThread() : Thread() { aoqi@0: _name = NULL; aoqi@0: _processed_thread = NULL; aoqi@0: } aoqi@0: aoqi@0: NamedThread::~NamedThread() { aoqi@0: if (_name != NULL) { aoqi@0: FREE_C_HEAP_ARRAY(char, _name, mtThread); aoqi@0: _name = NULL; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void NamedThread::set_name(const char* format, ...) { aoqi@0: guarantee(_name == NULL, "Only get to set name once."); aoqi@0: _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread); aoqi@0: guarantee(_name != NULL, "alloc failure"); aoqi@0: va_list ap; aoqi@0: va_start(ap, format); aoqi@0: jio_vsnprintf(_name, max_name_len, format, ap); aoqi@0: va_end(ap); aoqi@0: } aoqi@0: aoqi@0: // ======= WatcherThread ======== aoqi@0: aoqi@0: // The watcher thread exists to simulate timer interrupts. It should aoqi@0: // be replaced by an abstraction over whatever native support for aoqi@0: // timer interrupts exists on the platform. aoqi@0: aoqi@0: WatcherThread* WatcherThread::_watcher_thread = NULL; aoqi@0: bool WatcherThread::_startable = false; aoqi@0: volatile bool WatcherThread::_should_terminate = false; aoqi@0: aoqi@0: WatcherThread::WatcherThread() : Thread(), _crash_protection(NULL) { aoqi@0: assert(watcher_thread() == NULL, "we can only allocate one WatcherThread"); aoqi@0: if (os::create_thread(this, os::watcher_thread)) { aoqi@0: _watcher_thread = this; aoqi@0: aoqi@0: // Set the watcher thread to the highest OS priority which should not be aoqi@0: // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY aoqi@0: // is created. The only normal thread using this priority is the reference aoqi@0: // handler thread, which runs for very short intervals only. aoqi@0: // If the VMThread's priority is not lower than the WatcherThread profiling aoqi@0: // will be inaccurate. aoqi@0: os::set_priority(this, MaxPriority); aoqi@0: if (!DisableStartThread) { aoqi@0: os::start_thread(this); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: int WatcherThread::sleep() const { aoqi@0: MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag); aoqi@0: aoqi@0: // remaining will be zero if there are no tasks, aoqi@0: // causing the WatcherThread to sleep until a task is aoqi@0: // enrolled aoqi@0: int remaining = PeriodicTask::time_to_wait(); aoqi@0: int time_slept = 0; aoqi@0: aoqi@0: // we expect this to timeout - we only ever get unparked when aoqi@0: // we should terminate or when a new task has been enrolled aoqi@0: OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */); aoqi@0: aoqi@0: jlong time_before_loop = os::javaTimeNanos(); aoqi@0: aoqi@0: for (;;) { aoqi@0: bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag, remaining); aoqi@0: jlong now = os::javaTimeNanos(); aoqi@0: aoqi@0: if (remaining == 0) { aoqi@0: // if we didn't have any tasks we could have waited for a long time aoqi@0: // consider the time_slept zero and reset time_before_loop aoqi@0: time_slept = 0; aoqi@0: time_before_loop = now; aoqi@0: } else { aoqi@0: // need to recalulate since we might have new tasks in _tasks aoqi@0: time_slept = (int) ((now - time_before_loop) / 1000000); aoqi@0: } aoqi@0: aoqi@0: // Change to task list or spurious wakeup of some kind aoqi@0: if (timedout || _should_terminate) { aoqi@0: break; aoqi@0: } aoqi@0: aoqi@0: remaining = PeriodicTask::time_to_wait(); aoqi@0: if (remaining == 0) { aoqi@0: // Last task was just disenrolled so loop around and wait until aoqi@0: // another task gets enrolled aoqi@0: continue; aoqi@0: } aoqi@0: aoqi@0: remaining -= time_slept; aoqi@0: if (remaining <= 0) aoqi@0: break; aoqi@0: } aoqi@0: aoqi@0: return time_slept; aoqi@0: } aoqi@0: aoqi@0: void WatcherThread::run() { aoqi@0: assert(this == watcher_thread(), "just checking"); aoqi@0: aoqi@0: this->record_stack_base_and_size(); aoqi@0: this->initialize_thread_local_storage(); aoqi@0: this->set_active_handles(JNIHandleBlock::allocate_block()); aoqi@0: while(!_should_terminate) { aoqi@0: assert(watcher_thread() == Thread::current(), "thread consistency check"); aoqi@0: assert(watcher_thread() == this, "thread consistency check"); aoqi@0: aoqi@0: // Calculate how long it'll be until the next PeriodicTask work aoqi@0: // should be done, and sleep that amount of time. aoqi@0: int time_waited = sleep(); aoqi@0: aoqi@0: if (is_error_reported()) { aoqi@0: // A fatal error has happened, the error handler(VMError::report_and_die) aoqi@0: // should abort JVM after creating an error log file. However in some aoqi@0: // rare cases, the error handler itself might deadlock. Here we try to aoqi@0: // kill JVM if the fatal error handler fails to abort in 2 minutes. aoqi@0: // aoqi@0: // This code is in WatcherThread because WatcherThread wakes up aoqi@0: // periodically so the fatal error handler doesn't need to do anything; aoqi@0: // also because the WatcherThread is less likely to crash than other aoqi@0: // threads. aoqi@0: aoqi@0: for (;;) { aoqi@0: if (!ShowMessageBoxOnError aoqi@0: && (OnError == NULL || OnError[0] == '\0') aoqi@0: && Arguments::abort_hook() == NULL) { aoqi@0: os::sleep(this, 2 * 60 * 1000, false); aoqi@0: fdStream err(defaultStream::output_fd()); aoqi@0: err.print_raw_cr("# [ timer expired, abort... ]"); aoqi@0: // skip atexit/vm_exit/vm_abort hooks aoqi@0: os::die(); aoqi@0: } aoqi@0: aoqi@0: // Wake up 5 seconds later, the fatal handler may reset OnError or aoqi@0: // ShowMessageBoxOnError when it is ready to abort. aoqi@0: os::sleep(this, 5 * 1000, false); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: PeriodicTask::real_time_tick(time_waited); aoqi@0: } aoqi@0: aoqi@0: // Signal that it is terminated aoqi@0: { aoqi@0: MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag); aoqi@0: _watcher_thread = NULL; aoqi@0: Terminator_lock->notify(); aoqi@0: } aoqi@0: aoqi@0: // Thread destructor usually does this.. aoqi@0: ThreadLocalStorage::set_thread(NULL); aoqi@0: } aoqi@0: aoqi@0: void WatcherThread::start() { aoqi@0: assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); aoqi@0: aoqi@0: if (watcher_thread() == NULL && _startable) { aoqi@0: _should_terminate = false; aoqi@0: // Create the single instance of WatcherThread aoqi@0: new WatcherThread(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void WatcherThread::make_startable() { aoqi@0: assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); aoqi@0: _startable = true; aoqi@0: } aoqi@0: aoqi@0: void WatcherThread::stop() { aoqi@0: { aoqi@0: MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag); aoqi@0: _should_terminate = true; aoqi@0: OrderAccess::fence(); // ensure WatcherThread sees update in main loop aoqi@0: aoqi@0: WatcherThread* watcher = watcher_thread(); aoqi@0: if (watcher != NULL) aoqi@0: watcher->unpark(); aoqi@0: } aoqi@0: aoqi@0: // it is ok to take late safepoints here, if needed aoqi@0: MutexLocker mu(Terminator_lock); aoqi@0: aoqi@0: while(watcher_thread() != NULL) { aoqi@0: // This wait should make safepoint checks, wait without a timeout, aoqi@0: // and wait as a suspend-equivalent condition. aoqi@0: // aoqi@0: // Note: If the FlatProfiler is running, then this thread is waiting aoqi@0: // for the WatcherThread to terminate and the WatcherThread, via the aoqi@0: // FlatProfiler task, is waiting for the external suspend request on aoqi@0: // this thread to complete. wait_for_ext_suspend_completion() will aoqi@0: // eventually timeout, but that takes time. Making this wait a aoqi@0: // suspend-equivalent condition solves that timeout problem. aoqi@0: // aoqi@0: Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0, aoqi@0: Mutex::_as_suspend_equivalent_flag); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void WatcherThread::unpark() { aoqi@0: MutexLockerEx ml(PeriodicTask_lock->owned_by_self() ? NULL : PeriodicTask_lock, Mutex::_no_safepoint_check_flag); aoqi@0: PeriodicTask_lock->notify(); aoqi@0: } aoqi@0: aoqi@0: void WatcherThread::print_on(outputStream* st) const { aoqi@0: st->print("\"%s\" ", name()); aoqi@0: Thread::print_on(st); aoqi@0: st->cr(); aoqi@0: } aoqi@0: aoqi@0: // ======= JavaThread ======== aoqi@0: aoqi@0: // A JavaThread is a normal Java thread aoqi@0: aoqi@0: void JavaThread::initialize() { aoqi@0: // Initialize fields aoqi@0: aoqi@0: // Set the claimed par_id to UINT_MAX (ie not claiming any par_ids) aoqi@0: set_claimed_par_id(UINT_MAX); aoqi@0: aoqi@0: set_saved_exception_pc(NULL); aoqi@0: set_threadObj(NULL); aoqi@0: _anchor.clear(); aoqi@0: set_entry_point(NULL); aoqi@0: set_jni_functions(jni_functions()); aoqi@0: set_callee_target(NULL); aoqi@0: set_vm_result(NULL); aoqi@0: set_vm_result_2(NULL); aoqi@0: set_vframe_array_head(NULL); aoqi@0: set_vframe_array_last(NULL); aoqi@0: set_deferred_locals(NULL); aoqi@0: set_deopt_mark(NULL); aoqi@0: set_deopt_nmethod(NULL); aoqi@0: clear_must_deopt_id(); aoqi@0: set_monitor_chunks(NULL); aoqi@0: set_next(NULL); aoqi@0: set_thread_state(_thread_new); aoqi@0: #if INCLUDE_NMT aoqi@0: set_recorder(NULL); aoqi@0: #endif aoqi@0: _terminated = _not_terminated; aoqi@0: _privileged_stack_top = NULL; aoqi@0: _array_for_gc = NULL; aoqi@0: _suspend_equivalent = false; aoqi@0: _in_deopt_handler = 0; aoqi@0: _doing_unsafe_access = false; aoqi@0: _stack_guard_state = stack_guard_unused; aoqi@0: (void)const_cast(_exception_oop = NULL); aoqi@0: _exception_pc = 0; aoqi@0: _exception_handler_pc = 0; aoqi@0: _is_method_handle_return = 0; aoqi@0: _jvmti_thread_state= NULL; aoqi@0: _should_post_on_exceptions_flag = JNI_FALSE; aoqi@0: _jvmti_get_loaded_classes_closure = NULL; aoqi@0: _interp_only_mode = 0; aoqi@0: _special_runtime_exit_condition = _no_async_condition; aoqi@0: _pending_async_exception = NULL; aoqi@0: _thread_stat = NULL; aoqi@0: _thread_stat = new ThreadStatistics(); aoqi@0: _blocked_on_compilation = false; aoqi@0: _jni_active_critical = 0; aoqi@0: _do_not_unlock_if_synchronized = false; aoqi@0: _cached_monitor_info = NULL; aoqi@0: _parker = Parker::Allocate(this) ; aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: _jmp_ring_index = 0; aoqi@0: for (int ji = 0 ; ji < jump_ring_buffer_size ; ji++ ) { aoqi@0: record_jump(NULL, NULL, NULL, 0); aoqi@0: } aoqi@0: #endif /* PRODUCT */ aoqi@0: aoqi@0: set_thread_profiler(NULL); aoqi@0: if (FlatProfiler::is_active()) { aoqi@0: // This is where we would decide to either give each thread it's own profiler aoqi@0: // or use one global one from FlatProfiler, aoqi@0: // or up to some count of the number of profiled threads, etc. aoqi@0: ThreadProfiler* pp = new ThreadProfiler(); aoqi@0: pp->engage(); aoqi@0: set_thread_profiler(pp); aoqi@0: } aoqi@0: aoqi@0: // Setup safepoint state info for this thread aoqi@0: ThreadSafepointState::create(this); aoqi@0: aoqi@0: debug_only(_java_call_counter = 0); aoqi@0: aoqi@0: // JVMTI PopFrame support aoqi@0: _popframe_condition = popframe_inactive; aoqi@0: _popframe_preserved_args = NULL; aoqi@0: _popframe_preserved_args_size = 0; aoqi@0: aoqi@0: pd_initialize(); aoqi@0: } aoqi@0: aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: SATBMarkQueueSet JavaThread::_satb_mark_queue_set; aoqi@0: DirtyCardQueueSet JavaThread::_dirty_card_queue_set; aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: aoqi@0: JavaThread::JavaThread(bool is_attaching_via_jni) : aoqi@0: Thread() aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: , _satb_mark_queue(&_satb_mark_queue_set), aoqi@0: _dirty_card_queue(&_dirty_card_queue_set) aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: { aoqi@0: initialize(); aoqi@0: if (is_attaching_via_jni) { aoqi@0: _jni_attach_state = _attaching_via_jni; aoqi@0: } else { aoqi@0: _jni_attach_state = _not_attaching_via_jni; aoqi@0: } aoqi@0: assert(deferred_card_mark().is_empty(), "Default MemRegion ctor"); aoqi@0: _safepoint_visible = false; aoqi@0: } aoqi@0: aoqi@0: bool JavaThread::reguard_stack(address cur_sp) { aoqi@0: if (_stack_guard_state != stack_guard_yellow_disabled) { aoqi@0: return true; // Stack already guarded or guard pages not needed. aoqi@0: } aoqi@0: aoqi@0: if (register_stack_overflow()) { aoqi@0: // For those architectures which have separate register and aoqi@0: // memory stacks, we must check the register stack to see if aoqi@0: // it has overflowed. aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: // Java code never executes within the yellow zone: the latter is only aoqi@0: // there to provoke an exception during stack banging. If java code aoqi@0: // is executing there, either StackShadowPages should be larger, or aoqi@0: // some exception code in c1, c2 or the interpreter isn't unwinding aoqi@0: // when it should. aoqi@0: guarantee(cur_sp > stack_yellow_zone_base(), "not enough space to reguard - increase StackShadowPages"); aoqi@0: aoqi@0: enable_stack_yellow_zone(); aoqi@0: return true; aoqi@0: } aoqi@0: aoqi@0: bool JavaThread::reguard_stack(void) { aoqi@0: return reguard_stack(os::current_stack_pointer()); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void JavaThread::block_if_vm_exited() { aoqi@0: if (_terminated == _vm_exited) { aoqi@0: // _vm_exited is set at safepoint, and Threads_lock is never released aoqi@0: // we will block here forever aoqi@0: Threads_lock->lock_without_safepoint_check(); aoqi@0: ShouldNotReachHere(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // Remove this ifdef when C1 is ported to the compiler interface. aoqi@0: static void compiler_thread_entry(JavaThread* thread, TRAPS); aoqi@0: aoqi@0: JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : aoqi@0: Thread() aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: , _satb_mark_queue(&_satb_mark_queue_set), aoqi@0: _dirty_card_queue(&_dirty_card_queue_set) aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: { aoqi@0: if (TraceThreadEvents) { aoqi@0: tty->print_cr("creating thread %p", this); aoqi@0: } aoqi@0: initialize(); aoqi@0: _jni_attach_state = _not_attaching_via_jni; aoqi@0: set_entry_point(entry_point); aoqi@0: // Create the native thread itself. aoqi@0: // %note runtime_23 aoqi@0: os::ThreadType thr_type = os::java_thread; aoqi@0: thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread : aoqi@0: os::java_thread; aoqi@0: os::create_thread(this, thr_type, stack_sz); aoqi@0: _safepoint_visible = false; aoqi@0: // The _osthread may be NULL here because we ran out of memory (too many threads active). aoqi@0: // We need to throw and OutOfMemoryError - however we cannot do this here because the caller aoqi@0: // may hold a lock and all locks must be unlocked before throwing the exception (throwing aoqi@0: // the exception consists of creating the exception object & initializing it, initialization aoqi@0: // will leave the VM via a JavaCall and then all locks must be unlocked). aoqi@0: // aoqi@0: // The thread is still suspended when we reach here. Thread must be explicit started aoqi@0: // by creator! Furthermore, the thread must also explicitly be added to the Threads list aoqi@0: // by calling Threads:add. The reason why this is not done here, is because the thread aoqi@0: // object must be fully initialized (take a look at JVM_Start) aoqi@0: } aoqi@0: aoqi@0: JavaThread::~JavaThread() { aoqi@0: if (TraceThreadEvents) { aoqi@0: tty->print_cr("terminate thread %p", this); aoqi@0: } aoqi@0: aoqi@0: // By now, this thread should already be invisible to safepoint, aoqi@0: // and its per-thread recorder also collected. aoqi@0: assert(!is_safepoint_visible(), "wrong state"); aoqi@0: #if INCLUDE_NMT aoqi@0: assert(get_recorder() == NULL, "Already collected"); aoqi@0: #endif // INCLUDE_NMT aoqi@0: aoqi@0: // JSR166 -- return the parker to the free list aoqi@0: Parker::Release(_parker); aoqi@0: _parker = NULL ; aoqi@0: aoqi@0: // Free any remaining previous UnrollBlock aoqi@0: vframeArray* old_array = vframe_array_last(); aoqi@0: aoqi@0: if (old_array != NULL) { aoqi@0: Deoptimization::UnrollBlock* old_info = old_array->unroll_block(); aoqi@0: old_array->set_unroll_block(NULL); aoqi@0: delete old_info; aoqi@0: delete old_array; aoqi@0: } aoqi@0: aoqi@0: GrowableArray* deferred = deferred_locals(); aoqi@0: if (deferred != NULL) { aoqi@0: // This can only happen if thread is destroyed before deoptimization occurs. aoqi@0: assert(deferred->length() != 0, "empty array!"); aoqi@0: do { aoqi@0: jvmtiDeferredLocalVariableSet* dlv = deferred->at(0); aoqi@0: deferred->remove_at(0); aoqi@0: // individual jvmtiDeferredLocalVariableSet are CHeapObj's aoqi@0: delete dlv; aoqi@0: } while (deferred->length() != 0); aoqi@0: delete deferred; aoqi@0: } aoqi@0: aoqi@0: // All Java related clean up happens in exit aoqi@0: ThreadSafepointState::destroy(this); aoqi@0: if (_thread_profiler != NULL) delete _thread_profiler; aoqi@0: if (_thread_stat != NULL) delete _thread_stat; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // The first routine called by a new Java thread aoqi@0: void JavaThread::run() { aoqi@0: // initialize thread-local alloc buffer related fields aoqi@0: this->initialize_tlab(); aoqi@0: aoqi@0: // used to test validitity of stack trace backs aoqi@0: this->record_base_of_stack_pointer(); aoqi@0: aoqi@0: // Record real stack base and size. aoqi@0: this->record_stack_base_and_size(); aoqi@0: aoqi@0: // Initialize thread local storage; set before calling MutexLocker aoqi@0: this->initialize_thread_local_storage(); aoqi@0: aoqi@0: this->create_stack_guard_pages(); aoqi@0: aoqi@0: this->cache_global_variables(); aoqi@0: aoqi@0: // Thread is now sufficient initialized to be handled by the safepoint code as being aoqi@0: // in the VM. Change thread state from _thread_new to _thread_in_vm aoqi@0: ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm); aoqi@0: aoqi@0: assert(JavaThread::current() == this, "sanity check"); aoqi@0: assert(!Thread::current()->owns_locks(), "sanity check"); aoqi@0: aoqi@0: DTRACE_THREAD_PROBE(start, this); aoqi@0: aoqi@0: // This operation might block. We call that after all safepoint checks for a new thread has aoqi@0: // been completed. aoqi@0: this->set_active_handles(JNIHandleBlock::allocate_block()); aoqi@0: aoqi@0: if (JvmtiExport::should_post_thread_life()) { aoqi@0: JvmtiExport::post_thread_start(this); aoqi@0: } aoqi@0: aoqi@0: EventThreadStart event; aoqi@0: if (event.should_commit()) { aoqi@0: event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj())); aoqi@0: event.commit(); aoqi@0: } aoqi@0: aoqi@0: // We call another function to do the rest so we are sure that the stack addresses used aoqi@0: // from there will be lower than the stack base just computed aoqi@0: thread_main_inner(); aoqi@0: aoqi@0: // Note, thread is no longer valid at this point! aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void JavaThread::thread_main_inner() { aoqi@0: assert(JavaThread::current() == this, "sanity check"); aoqi@0: assert(this->threadObj() != NULL, "just checking"); aoqi@0: aoqi@0: // Execute thread entry point unless this thread has a pending exception aoqi@0: // or has been stopped before starting. aoqi@0: // Note: Due to JVM_StopThread we can have pending exceptions already! aoqi@0: if (!this->has_pending_exception() && aoqi@0: !java_lang_Thread::is_stillborn(this->threadObj())) { aoqi@0: { aoqi@0: ResourceMark rm(this); aoqi@0: this->set_native_thread_name(this->get_thread_name()); aoqi@0: } aoqi@0: HandleMark hm(this); aoqi@0: this->entry_point()(this, this); aoqi@0: } aoqi@0: aoqi@0: DTRACE_THREAD_PROBE(stop, this); aoqi@0: aoqi@0: this->exit(false); aoqi@0: delete this; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: static void ensure_join(JavaThread* thread) { aoqi@0: // We do not need to grap the Threads_lock, since we are operating on ourself. aoqi@0: Handle threadObj(thread, thread->threadObj()); aoqi@0: assert(threadObj.not_null(), "java thread object must exist"); aoqi@0: ObjectLocker lock(threadObj, thread); aoqi@0: // Ignore pending exception (ThreadDeath), since we are exiting anyway aoqi@0: thread->clear_pending_exception(); aoqi@0: // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED. aoqi@0: java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED); aoqi@0: // Clear the native thread instance - this makes isAlive return false and allows the join() aoqi@0: // to complete once we've done the notify_all below aoqi@0: java_lang_Thread::set_thread(threadObj(), NULL); aoqi@0: lock.notify_all(thread); aoqi@0: // Ignore pending exception (ThreadDeath), since we are exiting anyway aoqi@0: thread->clear_pending_exception(); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // For any new cleanup additions, please check to see if they need to be applied to aoqi@0: // cleanup_failed_attach_current_thread as well. aoqi@0: void JavaThread::exit(bool destroy_vm, ExitType exit_type) { aoqi@0: assert(this == JavaThread::current(), "thread consistency check"); aoqi@0: aoqi@0: HandleMark hm(this); aoqi@0: Handle uncaught_exception(this, this->pending_exception()); aoqi@0: this->clear_pending_exception(); aoqi@0: Handle threadObj(this, this->threadObj()); aoqi@0: assert(threadObj.not_null(), "Java thread object should be created"); aoqi@0: aoqi@0: if (get_thread_profiler() != NULL) { aoqi@0: get_thread_profiler()->disengage(); aoqi@0: ResourceMark rm; aoqi@0: get_thread_profiler()->print(get_thread_name()); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place aoqi@0: { aoqi@0: EXCEPTION_MARK; aoqi@0: aoqi@0: CLEAR_PENDING_EXCEPTION; aoqi@0: } aoqi@0: // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This aoqi@0: // has to be fixed by a runtime query method aoqi@0: if (!destroy_vm || JDK_Version::is_jdk12x_version()) { aoqi@0: // JSR-166: change call from from ThreadGroup.uncaughtException to aoqi@0: // java.lang.Thread.dispatchUncaughtException aoqi@0: if (uncaught_exception.not_null()) { aoqi@0: Handle group(this, java_lang_Thread::threadGroup(threadObj())); aoqi@0: { aoqi@0: EXCEPTION_MARK; aoqi@0: // Check if the method Thread.dispatchUncaughtException() exists. If so aoqi@0: // call it. Otherwise we have an older library without the JSR-166 changes, aoqi@0: // so call ThreadGroup.uncaughtException() aoqi@0: KlassHandle recvrKlass(THREAD, threadObj->klass()); aoqi@0: CallInfo callinfo; aoqi@0: KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass()); aoqi@0: LinkResolver::resolve_virtual_call(callinfo, threadObj, recvrKlass, thread_klass, aoqi@0: vmSymbols::dispatchUncaughtException_name(), aoqi@0: vmSymbols::throwable_void_signature(), aoqi@0: KlassHandle(), false, false, THREAD); aoqi@0: CLEAR_PENDING_EXCEPTION; aoqi@0: methodHandle method = callinfo.selected_method(); aoqi@0: if (method.not_null()) { aoqi@0: JavaValue result(T_VOID); aoqi@0: JavaCalls::call_virtual(&result, aoqi@0: threadObj, thread_klass, aoqi@0: vmSymbols::dispatchUncaughtException_name(), aoqi@0: vmSymbols::throwable_void_signature(), aoqi@0: uncaught_exception, aoqi@0: THREAD); aoqi@0: } else { aoqi@0: KlassHandle thread_group(THREAD, SystemDictionary::ThreadGroup_klass()); aoqi@0: JavaValue result(T_VOID); aoqi@0: JavaCalls::call_virtual(&result, aoqi@0: group, thread_group, aoqi@0: vmSymbols::uncaughtException_name(), aoqi@0: vmSymbols::thread_throwable_void_signature(), aoqi@0: threadObj, // Arg 1 aoqi@0: uncaught_exception, // Arg 2 aoqi@0: THREAD); aoqi@0: } aoqi@0: if (HAS_PENDING_EXCEPTION) { aoqi@0: ResourceMark rm(this); aoqi@0: jio_fprintf(defaultStream::error_stream(), aoqi@0: "\nException: %s thrown from the UncaughtExceptionHandler" aoqi@0: " in thread \"%s\"\n", aoqi@0: pending_exception()->klass()->external_name(), aoqi@0: get_thread_name()); aoqi@0: CLEAR_PENDING_EXCEPTION; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Called before the java thread exit since we want to read info aoqi@0: // from java_lang_Thread object aoqi@0: EventThreadEnd event; aoqi@0: if (event.should_commit()) { aoqi@0: event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj())); aoqi@0: event.commit(); aoqi@0: } aoqi@0: aoqi@0: // Call after last event on thread aoqi@0: EVENT_THREAD_EXIT(this); aoqi@0: aoqi@0: // Call Thread.exit(). We try 3 times in case we got another Thread.stop during aoqi@0: // the execution of the method. If that is not enough, then we don't really care. Thread.stop aoqi@0: // is deprecated anyhow. aoqi@0: if (!is_Compiler_thread()) { aoqi@0: int count = 3; aoqi@0: while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) { aoqi@0: EXCEPTION_MARK; aoqi@0: JavaValue result(T_VOID); aoqi@0: KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass()); aoqi@0: JavaCalls::call_virtual(&result, aoqi@0: threadObj, thread_klass, aoqi@0: vmSymbols::exit_method_name(), aoqi@0: vmSymbols::void_method_signature(), aoqi@0: THREAD); aoqi@0: CLEAR_PENDING_EXCEPTION; aoqi@0: } aoqi@0: } aoqi@0: // notify JVMTI aoqi@0: if (JvmtiExport::should_post_thread_life()) { aoqi@0: JvmtiExport::post_thread_end(this); aoqi@0: } aoqi@0: aoqi@0: // We have notified the agents that we are exiting, before we go on, aoqi@0: // we must check for a pending external suspend request and honor it aoqi@0: // in order to not surprise the thread that made the suspend request. aoqi@0: while (true) { aoqi@0: { aoqi@0: MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); aoqi@0: if (!is_external_suspend()) { aoqi@0: set_terminated(_thread_exiting); aoqi@0: ThreadService::current_thread_exiting(this); aoqi@0: break; aoqi@0: } aoqi@0: // Implied else: aoqi@0: // Things get a little tricky here. We have a pending external aoqi@0: // suspend request, but we are holding the SR_lock so we aoqi@0: // can't just self-suspend. So we temporarily drop the lock aoqi@0: // and then self-suspend. aoqi@0: } aoqi@0: aoqi@0: ThreadBlockInVM tbivm(this); aoqi@0: java_suspend_self(); aoqi@0: aoqi@0: // We're done with this suspend request, but we have to loop around aoqi@0: // and check again. Eventually we will get SR_lock without a pending aoqi@0: // external suspend request and will be able to mark ourselves as aoqi@0: // exiting. aoqi@0: } aoqi@0: // no more external suspends are allowed at this point aoqi@0: } else { aoqi@0: // before_exit() has already posted JVMTI THREAD_END events aoqi@0: } aoqi@0: aoqi@0: // Notify waiters on thread object. This has to be done after exit() is called aoqi@0: // on the thread (if the thread is the last thread in a daemon ThreadGroup the aoqi@0: // group should have the destroyed bit set before waiters are notified). aoqi@0: ensure_join(this); aoqi@0: assert(!this->has_pending_exception(), "ensure_join should have cleared"); aoqi@0: aoqi@0: // 6282335 JNI DetachCurrentThread spec states that all Java monitors aoqi@0: // held by this thread must be released. A detach operation must only aoqi@0: // get here if there are no Java frames on the stack. Therefore, any aoqi@0: // owned monitors at this point MUST be JNI-acquired monitors which are aoqi@0: // pre-inflated and in the monitor cache. aoqi@0: // aoqi@0: // ensure_join() ignores IllegalThreadStateExceptions, and so does this. aoqi@0: if (exit_type == jni_detach && JNIDetachReleasesMonitors) { aoqi@0: assert(!this->has_last_Java_frame(), "detaching with Java frames?"); aoqi@0: ObjectSynchronizer::release_monitors_owned_by_thread(this); aoqi@0: assert(!this->has_pending_exception(), "release_monitors should have cleared"); aoqi@0: } aoqi@0: aoqi@0: // These things needs to be done while we are still a Java Thread. Make sure that thread aoqi@0: // is in a consistent state, in case GC happens aoqi@0: assert(_privileged_stack_top == NULL, "must be NULL when we get here"); aoqi@0: aoqi@0: if (active_handles() != NULL) { aoqi@0: JNIHandleBlock* block = active_handles(); aoqi@0: set_active_handles(NULL); aoqi@0: JNIHandleBlock::release_block(block); aoqi@0: } aoqi@0: aoqi@0: if (free_handle_block() != NULL) { aoqi@0: JNIHandleBlock* block = free_handle_block(); aoqi@0: set_free_handle_block(NULL); aoqi@0: JNIHandleBlock::release_block(block); aoqi@0: } aoqi@0: aoqi@0: // These have to be removed while this is still a valid thread. aoqi@0: remove_stack_guard_pages(); aoqi@0: aoqi@0: if (UseTLAB) { aoqi@0: tlab().make_parsable(true); // retire TLAB aoqi@0: } aoqi@0: aoqi@0: if (JvmtiEnv::environments_might_exist()) { aoqi@0: JvmtiExport::cleanup_thread(this); aoqi@0: } aoqi@0: aoqi@0: // We must flush any deferred card marks before removing a thread from aoqi@0: // the list of active threads. aoqi@0: Universe::heap()->flush_deferred_store_barrier(this); aoqi@0: assert(deferred_card_mark().is_empty(), "Should have been flushed"); aoqi@0: aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: // We must flush the G1-related buffers before removing a thread aoqi@0: // from the list of active threads. We must do this after any deferred aoqi@0: // card marks have been flushed (above) so that any entries that are aoqi@0: // added to the thread's dirty card queue as a result are not lost. aoqi@0: if (UseG1GC) { aoqi@0: flush_barrier_queues(); aoqi@0: } aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: aoqi@0: // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread aoqi@0: Threads::remove(this); aoqi@0: } aoqi@0: aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: // Flush G1-related queues. aoqi@0: void JavaThread::flush_barrier_queues() { aoqi@0: satb_mark_queue().flush(); aoqi@0: dirty_card_queue().flush(); aoqi@0: } aoqi@0: aoqi@0: void JavaThread::initialize_queues() { aoqi@0: assert(!SafepointSynchronize::is_at_safepoint(), aoqi@0: "we should not be at a safepoint"); aoqi@0: aoqi@0: ObjPtrQueue& satb_queue = satb_mark_queue(); aoqi@0: SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set(); aoqi@0: // The SATB queue should have been constructed with its active aoqi@0: // field set to false. aoqi@0: assert(!satb_queue.is_active(), "SATB queue should not be active"); aoqi@0: assert(satb_queue.is_empty(), "SATB queue should be empty"); aoqi@0: // If we are creating the thread during a marking cycle, we should aoqi@0: // set the active field of the SATB queue to true. aoqi@0: if (satb_queue_set.is_active()) { aoqi@0: satb_queue.set_active(true); aoqi@0: } aoqi@0: aoqi@0: DirtyCardQueue& dirty_queue = dirty_card_queue(); aoqi@0: // The dirty card queue should have been constructed with its aoqi@0: // active field set to true. aoqi@0: assert(dirty_queue.is_active(), "dirty card queue should be active"); aoqi@0: } aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: aoqi@0: void JavaThread::cleanup_failed_attach_current_thread() { aoqi@0: if (get_thread_profiler() != NULL) { aoqi@0: get_thread_profiler()->disengage(); aoqi@0: ResourceMark rm; aoqi@0: get_thread_profiler()->print(get_thread_name()); aoqi@0: } aoqi@0: aoqi@0: if (active_handles() != NULL) { aoqi@0: JNIHandleBlock* block = active_handles(); aoqi@0: set_active_handles(NULL); aoqi@0: JNIHandleBlock::release_block(block); aoqi@0: } aoqi@0: aoqi@0: if (free_handle_block() != NULL) { aoqi@0: JNIHandleBlock* block = free_handle_block(); aoqi@0: set_free_handle_block(NULL); aoqi@0: JNIHandleBlock::release_block(block); aoqi@0: } aoqi@0: aoqi@0: // These have to be removed while this is still a valid thread. aoqi@0: remove_stack_guard_pages(); aoqi@0: aoqi@0: if (UseTLAB) { aoqi@0: tlab().make_parsable(true); // retire TLAB, if any aoqi@0: } aoqi@0: aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: if (UseG1GC) { aoqi@0: flush_barrier_queues(); aoqi@0: } aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: aoqi@0: Threads::remove(this); aoqi@0: delete this; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: aoqi@0: aoqi@0: JavaThread* JavaThread::active() { aoqi@0: Thread* thread = ThreadLocalStorage::thread(); aoqi@0: assert(thread != NULL, "just checking"); aoqi@0: if (thread->is_Java_thread()) { aoqi@0: return (JavaThread*) thread; aoqi@0: } else { aoqi@0: assert(thread->is_VM_thread(), "this must be a vm thread"); aoqi@0: VM_Operation* op = ((VMThread*) thread)->vm_operation(); aoqi@0: JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread(); aoqi@0: assert(ret->is_Java_thread(), "must be a Java thread"); aoqi@0: return ret; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: bool JavaThread::is_lock_owned(address adr) const { aoqi@0: if (Thread::is_lock_owned(adr)) return true; aoqi@0: aoqi@0: for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { aoqi@0: if (chunk->contains(adr)) return true; aoqi@0: } aoqi@0: aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void JavaThread::add_monitor_chunk(MonitorChunk* chunk) { aoqi@0: chunk->set_next(monitor_chunks()); aoqi@0: set_monitor_chunks(chunk); aoqi@0: } aoqi@0: aoqi@0: void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) { aoqi@0: guarantee(monitor_chunks() != NULL, "must be non empty"); aoqi@0: if (monitor_chunks() == chunk) { aoqi@0: set_monitor_chunks(chunk->next()); aoqi@0: } else { aoqi@0: MonitorChunk* prev = monitor_chunks(); aoqi@0: while (prev->next() != chunk) prev = prev->next(); aoqi@0: prev->set_next(chunk->next()); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // JVM support. aoqi@0: aoqi@0: // Note: this function shouldn't block if it's called in aoqi@0: // _thread_in_native_trans state (such as from aoqi@0: // check_special_condition_for_native_trans()). aoqi@0: void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) { aoqi@0: aoqi@0: if (has_last_Java_frame() && has_async_condition()) { aoqi@0: // If we are at a polling page safepoint (not a poll return) aoqi@0: // then we must defer async exception because live registers aoqi@0: // will be clobbered by the exception path. Poll return is aoqi@0: // ok because the call we a returning from already collides aoqi@0: // with exception handling registers and so there is no issue. aoqi@0: // (The exception handling path kills call result registers but aoqi@0: // this is ok since the exception kills the result anyway). aoqi@0: aoqi@0: if (is_at_poll_safepoint()) { aoqi@0: // if the code we are returning to has deoptimized we must defer aoqi@0: // the exception otherwise live registers get clobbered on the aoqi@0: // exception path before deoptimization is able to retrieve them. aoqi@0: // aoqi@0: RegisterMap map(this, false); aoqi@0: frame caller_fr = last_frame().sender(&map); aoqi@0: assert(caller_fr.is_compiled_frame(), "what?"); aoqi@0: if (caller_fr.is_deoptimized_frame()) { aoqi@0: if (TraceExceptions) { aoqi@0: ResourceMark rm; aoqi@0: tty->print_cr("deferred async exception at compiled safepoint"); aoqi@0: } aoqi@0: return; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition(); aoqi@0: if (condition == _no_async_condition) { aoqi@0: // Conditions have changed since has_special_runtime_exit_condition() aoqi@0: // was called: aoqi@0: // - if we were here only because of an external suspend request, aoqi@0: // then that was taken care of above (or cancelled) so we are done aoqi@0: // - if we were here because of another async request, then it has aoqi@0: // been cleared between the has_special_runtime_exit_condition() aoqi@0: // and now so again we are done aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: // Check for pending async. exception aoqi@0: if (_pending_async_exception != NULL) { aoqi@0: // Only overwrite an already pending exception, if it is not a threadDeath. aoqi@0: if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) { aoqi@0: aoqi@0: // We cannot call Exceptions::_throw(...) here because we cannot block aoqi@0: set_pending_exception(_pending_async_exception, __FILE__, __LINE__); aoqi@0: aoqi@0: if (TraceExceptions) { aoqi@0: ResourceMark rm; aoqi@0: tty->print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", this); aoqi@0: if (has_last_Java_frame() ) { aoqi@0: frame f = last_frame(); aoqi@0: tty->print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", f.pc(), f.sp()); aoqi@0: } aoqi@0: tty->print_cr(" of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name()); aoqi@0: } aoqi@0: _pending_async_exception = NULL; aoqi@0: clear_has_async_exception(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (check_unsafe_error && aoqi@0: condition == _async_unsafe_access_error && !has_pending_exception()) { aoqi@0: condition = _no_async_condition; // done aoqi@0: switch (thread_state()) { aoqi@0: case _thread_in_vm: aoqi@0: { aoqi@0: JavaThread* THREAD = this; aoqi@0: THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation"); aoqi@0: } aoqi@0: case _thread_in_native: aoqi@0: { aoqi@0: ThreadInVMfromNative tiv(this); aoqi@0: JavaThread* THREAD = this; aoqi@0: THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation"); aoqi@0: } aoqi@0: case _thread_in_Java: aoqi@0: { aoqi@0: ThreadInVMfromJava tiv(this); aoqi@0: JavaThread* THREAD = this; aoqi@0: THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code"); aoqi@0: } aoqi@0: default: aoqi@0: ShouldNotReachHere(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: assert(condition == _no_async_condition || has_pending_exception() || aoqi@0: (!check_unsafe_error && condition == _async_unsafe_access_error), aoqi@0: "must have handled the async condition, if no exception"); aoqi@0: } aoqi@0: aoqi@0: void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) { aoqi@0: // aoqi@0: // Check for pending external suspend. Internal suspend requests do aoqi@0: // not use handle_special_runtime_exit_condition(). aoqi@0: // If JNIEnv proxies are allowed, don't self-suspend if the target aoqi@0: // thread is not the current thread. In older versions of jdbx, jdbx aoqi@0: // threads could call into the VM with another thread's JNIEnv so we aoqi@0: // can be here operating on behalf of a suspended thread (4432884). aoqi@0: bool do_self_suspend = is_external_suspend_with_lock(); aoqi@0: if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) { aoqi@0: // aoqi@0: // Because thread is external suspended the safepoint code will count aoqi@0: // thread as at a safepoint. This can be odd because we can be here aoqi@0: // as _thread_in_Java which would normally transition to _thread_blocked aoqi@0: // at a safepoint. We would like to mark the thread as _thread_blocked aoqi@0: // before calling java_suspend_self like all other callers of it but aoqi@0: // we must then observe proper safepoint protocol. (We can't leave aoqi@0: // _thread_blocked with a safepoint in progress). However we can be aoqi@0: // here as _thread_in_native_trans so we can't use a normal transition aoqi@0: // constructor/destructor pair because they assert on that type of aoqi@0: // transition. We could do something like: aoqi@0: // aoqi@0: // JavaThreadState state = thread_state(); aoqi@0: // set_thread_state(_thread_in_vm); aoqi@0: // { aoqi@0: // ThreadBlockInVM tbivm(this); aoqi@0: // java_suspend_self() aoqi@0: // } aoqi@0: // set_thread_state(_thread_in_vm_trans); aoqi@0: // if (safepoint) block; aoqi@0: // set_thread_state(state); aoqi@0: // aoqi@0: // but that is pretty messy. Instead we just go with the way the aoqi@0: // code has worked before and note that this is the only path to aoqi@0: // java_suspend_self that doesn't put the thread in _thread_blocked aoqi@0: // mode. aoqi@0: aoqi@0: frame_anchor()->make_walkable(this); aoqi@0: java_suspend_self(); aoqi@0: aoqi@0: // We might be here for reasons in addition to the self-suspend request aoqi@0: // so check for other async requests. aoqi@0: } aoqi@0: aoqi@0: if (check_asyncs) { aoqi@0: check_and_handle_async_exceptions(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void JavaThread::send_thread_stop(oop java_throwable) { aoqi@0: assert(Thread::current()->is_VM_thread(), "should be in the vm thread"); aoqi@0: assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code"); aoqi@0: assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); aoqi@0: aoqi@0: // Do not throw asynchronous exceptions against the compiler thread aoqi@0: // (the compiler thread should not be a Java thread -- fix in 1.4.2) aoqi@0: if (is_Compiler_thread()) return; aoqi@0: aoqi@0: { aoqi@0: // Actually throw the Throwable against the target Thread - however aoqi@0: // only if there is no thread death exception installed already. aoqi@0: if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) { aoqi@0: // If the topmost frame is a runtime stub, then we are calling into aoqi@0: // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..) aoqi@0: // must deoptimize the caller before continuing, as the compiled exception handler table aoqi@0: // may not be valid aoqi@0: if (has_last_Java_frame()) { aoqi@0: frame f = last_frame(); aoqi@0: if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) { aoqi@0: // BiasedLocking needs an updated RegisterMap for the revoke monitors pass aoqi@0: RegisterMap reg_map(this, UseBiasedLocking); aoqi@0: frame compiled_frame = f.sender(®_map); aoqi@0: if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) { aoqi@0: Deoptimization::deoptimize(this, compiled_frame, ®_map); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Set async. pending exception in thread. aoqi@0: set_pending_async_exception(java_throwable); aoqi@0: aoqi@0: if (TraceExceptions) { aoqi@0: ResourceMark rm; aoqi@0: tty->print_cr("Pending Async. exception installed of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name()); aoqi@0: } aoqi@0: // for AbortVMOnException flag aoqi@0: NOT_PRODUCT(Exceptions::debug_check_abort(InstanceKlass::cast(_pending_async_exception->klass())->external_name())); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // Interrupt thread so it will wake up from a potential wait() aoqi@0: Thread::interrupt(this); aoqi@0: } aoqi@0: aoqi@0: // External suspension mechanism. aoqi@0: // aoqi@0: // Tell the VM to suspend a thread when ever it knows that it does not hold on aoqi@0: // to any VM_locks and it is at a transition aoqi@0: // Self-suspension will happen on the transition out of the vm. aoqi@0: // Catch "this" coming in from JNIEnv pointers when the thread has been freed aoqi@0: // aoqi@0: // Guarantees on return: aoqi@0: // + Target thread will not execute any new bytecode (that's why we need to aoqi@0: // force a safepoint) aoqi@0: // + Target thread will not enter any new monitors aoqi@0: // aoqi@0: void JavaThread::java_suspend() { aoqi@0: { MutexLocker mu(Threads_lock); aoqi@0: if (!Threads::includes(this) || is_exiting() || this->threadObj() == NULL) { aoqi@0: return; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); aoqi@0: if (!is_external_suspend()) { aoqi@0: // a racing resume has cancelled us; bail out now aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: // suspend is done aoqi@0: uint32_t debug_bits = 0; aoqi@0: // Warning: is_ext_suspend_completed() may temporarily drop the aoqi@0: // SR_lock to allow the thread to reach a stable thread state if aoqi@0: // it is currently in a transient thread state. aoqi@0: if (is_ext_suspend_completed(false /* !called_by_wait */, aoqi@0: SuspendRetryDelay, &debug_bits) ) { aoqi@0: return; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: VM_ForceSafepoint vm_suspend; aoqi@0: VMThread::execute(&vm_suspend); aoqi@0: } aoqi@0: aoqi@0: // Part II of external suspension. aoqi@0: // A JavaThread self suspends when it detects a pending external suspend aoqi@0: // request. This is usually on transitions. It is also done in places aoqi@0: // where continuing to the next transition would surprise the caller, aoqi@0: // e.g., monitor entry. aoqi@0: // aoqi@0: // Returns the number of times that the thread self-suspended. aoqi@0: // aoqi@0: // Note: DO NOT call java_suspend_self() when you just want to block current aoqi@0: // thread. java_suspend_self() is the second stage of cooperative aoqi@0: // suspension for external suspend requests and should only be used aoqi@0: // to complete an external suspend request. aoqi@0: // aoqi@0: int JavaThread::java_suspend_self() { aoqi@0: int ret = 0; aoqi@0: aoqi@0: // we are in the process of exiting so don't suspend aoqi@0: if (is_exiting()) { aoqi@0: clear_external_suspend(); aoqi@0: return ret; aoqi@0: } aoqi@0: aoqi@0: assert(_anchor.walkable() || aoqi@0: (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()), aoqi@0: "must have walkable stack"); aoqi@0: aoqi@0: MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); aoqi@0: aoqi@0: assert(!this->is_ext_suspended(), aoqi@0: "a thread trying to self-suspend should not already be suspended"); aoqi@0: aoqi@0: if (this->is_suspend_equivalent()) { aoqi@0: // If we are self-suspending as a result of the lifting of a aoqi@0: // suspend equivalent condition, then the suspend_equivalent aoqi@0: // flag is not cleared until we set the ext_suspended flag so aoqi@0: // that wait_for_ext_suspend_completion() returns consistent aoqi@0: // results. aoqi@0: this->clear_suspend_equivalent(); aoqi@0: } aoqi@0: aoqi@0: // A racing resume may have cancelled us before we grabbed SR_lock aoqi@0: // above. Or another external suspend request could be waiting for us aoqi@0: // by the time we return from SR_lock()->wait(). The thread aoqi@0: // that requested the suspension may already be trying to walk our aoqi@0: // stack and if we return now, we can change the stack out from under aoqi@0: // it. This would be a "bad thing (TM)" and cause the stack walker aoqi@0: // to crash. We stay self-suspended until there are no more pending aoqi@0: // external suspend requests. aoqi@0: while (is_external_suspend()) { aoqi@0: ret++; aoqi@0: this->set_ext_suspended(); aoqi@0: aoqi@0: // _ext_suspended flag is cleared by java_resume() aoqi@0: while (is_ext_suspended()) { aoqi@0: this->SR_lock()->wait(Mutex::_no_safepoint_check_flag); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: return ret; aoqi@0: } aoqi@0: aoqi@0: #ifdef ASSERT aoqi@0: // verify the JavaThread has not yet been published in the Threads::list, and aoqi@0: // hence doesn't need protection from concurrent access at this stage aoqi@0: void JavaThread::verify_not_published() { aoqi@0: if (!Threads_lock->owned_by_self()) { aoqi@0: MutexLockerEx ml(Threads_lock, Mutex::_no_safepoint_check_flag); aoqi@0: assert( !Threads::includes(this), aoqi@0: "java thread shouldn't have been published yet!"); aoqi@0: } aoqi@0: else { aoqi@0: assert( !Threads::includes(this), aoqi@0: "java thread shouldn't have been published yet!"); aoqi@0: } aoqi@0: } aoqi@0: #endif aoqi@0: aoqi@0: // Slow path when the native==>VM/Java barriers detect a safepoint is in aoqi@0: // progress or when _suspend_flags is non-zero. aoqi@0: // Current thread needs to self-suspend if there is a suspend request and/or aoqi@0: // block if a safepoint is in progress. aoqi@0: // Async exception ISN'T checked. aoqi@0: // Note only the ThreadInVMfromNative transition can call this function aoqi@0: // directly and when thread state is _thread_in_native_trans aoqi@0: void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) { aoqi@0: assert(thread->thread_state() == _thread_in_native_trans, "wrong state"); aoqi@0: aoqi@0: JavaThread *curJT = JavaThread::current(); aoqi@0: bool do_self_suspend = thread->is_external_suspend(); aoqi@0: aoqi@0: assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition"); aoqi@0: aoqi@0: // If JNIEnv proxies are allowed, don't self-suspend if the target aoqi@0: // thread is not the current thread. In older versions of jdbx, jdbx aoqi@0: // threads could call into the VM with another thread's JNIEnv so we aoqi@0: // can be here operating on behalf of a suspended thread (4432884). aoqi@0: if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) { aoqi@0: JavaThreadState state = thread->thread_state(); aoqi@0: aoqi@0: // We mark this thread_blocked state as a suspend-equivalent so aoqi@0: // that a caller to is_ext_suspend_completed() won't be confused. aoqi@0: // The suspend-equivalent state is cleared by java_suspend_self(). aoqi@0: thread->set_suspend_equivalent(); aoqi@0: aoqi@0: // If the safepoint code sees the _thread_in_native_trans state, it will aoqi@0: // wait until the thread changes to other thread state. There is no aoqi@0: // guarantee on how soon we can obtain the SR_lock and complete the aoqi@0: // self-suspend request. It would be a bad idea to let safepoint wait for aoqi@0: // too long. Temporarily change the state to _thread_blocked to aoqi@0: // let the VM thread know that this thread is ready for GC. The problem aoqi@0: // of changing thread state is that safepoint could happen just after aoqi@0: // java_suspend_self() returns after being resumed, and VM thread will aoqi@0: // see the _thread_blocked state. We must check for safepoint aoqi@0: // after restoring the state and make sure we won't leave while a safepoint aoqi@0: // is in progress. aoqi@0: thread->set_thread_state(_thread_blocked); aoqi@0: thread->java_suspend_self(); aoqi@0: thread->set_thread_state(state); aoqi@0: // Make sure new state is seen by VM thread aoqi@0: if (os::is_MP()) { aoqi@0: if (UseMembar) { aoqi@0: // Force a fence between the write above and read below aoqi@0: OrderAccess::fence(); aoqi@0: } else { aoqi@0: // Must use this rather than serialization page in particular on Windows aoqi@0: InterfaceSupport::serialize_memory(thread); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (SafepointSynchronize::do_call_back()) { aoqi@0: // If we are safepointing, then block the caller which may not be aoqi@0: // the same as the target thread (see above). aoqi@0: SafepointSynchronize::block(curJT); aoqi@0: } aoqi@0: aoqi@0: if (thread->is_deopt_suspend()) { aoqi@0: thread->clear_deopt_suspend(); aoqi@0: RegisterMap map(thread, false); aoqi@0: frame f = thread->last_frame(); aoqi@0: while ( f.id() != thread->must_deopt_id() && ! f.is_first_frame()) { aoqi@0: f = f.sender(&map); aoqi@0: } aoqi@0: if (f.id() == thread->must_deopt_id()) { aoqi@0: thread->clear_must_deopt_id(); aoqi@0: f.deoptimize(thread); aoqi@0: } else { aoqi@0: fatal("missed deoptimization!"); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Slow path when the native==>VM/Java barriers detect a safepoint is in aoqi@0: // progress or when _suspend_flags is non-zero. aoqi@0: // Current thread needs to self-suspend if there is a suspend request and/or aoqi@0: // block if a safepoint is in progress. aoqi@0: // Also check for pending async exception (not including unsafe access error). aoqi@0: // Note only the native==>VM/Java barriers can call this function and when aoqi@0: // thread state is _thread_in_native_trans. aoqi@0: void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) { aoqi@0: check_safepoint_and_suspend_for_native_trans(thread); aoqi@0: aoqi@0: if (thread->has_async_exception()) { aoqi@0: // We are in _thread_in_native_trans state, don't handle unsafe aoqi@0: // access error since that may block. aoqi@0: thread->check_and_handle_async_exceptions(false); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // This is a variant of the normal aoqi@0: // check_special_condition_for_native_trans with slightly different aoqi@0: // semantics for use by critical native wrappers. It does all the aoqi@0: // normal checks but also performs the transition back into aoqi@0: // thread_in_Java state. This is required so that critical natives aoqi@0: // can potentially block and perform a GC if they are the last thread aoqi@0: // exiting the GC_locker. aoqi@0: void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) { aoqi@0: check_special_condition_for_native_trans(thread); aoqi@0: aoqi@0: // Finish the transition aoqi@0: thread->set_thread_state(_thread_in_Java); aoqi@0: aoqi@0: if (thread->do_critical_native_unlock()) { aoqi@0: ThreadInVMfromJavaNoAsyncException tiv(thread); aoqi@0: GC_locker::unlock_critical(thread); aoqi@0: thread->clear_critical_native_unlock(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // We need to guarantee the Threads_lock here, since resumes are not aoqi@0: // allowed during safepoint synchronization aoqi@0: // Can only resume from an external suspension aoqi@0: void JavaThread::java_resume() { aoqi@0: assert_locked_or_safepoint(Threads_lock); aoqi@0: aoqi@0: // Sanity check: thread is gone, has started exiting or the thread aoqi@0: // was not externally suspended. aoqi@0: if (!Threads::includes(this) || is_exiting() || !is_external_suspend()) { aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); aoqi@0: aoqi@0: clear_external_suspend(); aoqi@0: aoqi@0: if (is_ext_suspended()) { aoqi@0: clear_ext_suspended(); aoqi@0: SR_lock()->notify_all(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void JavaThread::create_stack_guard_pages() { aoqi@0: if (! os::uses_stack_guard_pages() || _stack_guard_state != stack_guard_unused) return; aoqi@0: address low_addr = stack_base() - stack_size(); aoqi@0: size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size(); aoqi@0: aoqi@0: int allocate = os::allocate_stack_guard_pages(); aoqi@0: // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len); aoqi@0: aoqi@0: if (allocate && !os::create_stack_guard_pages((char *) low_addr, len)) { aoqi@0: warning("Attempt to allocate stack guard pages failed."); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: if (os::guard_memory((char *) low_addr, len)) { aoqi@0: _stack_guard_state = stack_guard_enabled; aoqi@0: } else { aoqi@0: warning("Attempt to protect stack guard pages failed."); aoqi@0: if (os::uncommit_memory((char *) low_addr, len)) { aoqi@0: warning("Attempt to deallocate stack guard pages failed."); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void JavaThread::remove_stack_guard_pages() { aoqi@0: assert(Thread::current() == this, "from different thread"); aoqi@0: if (_stack_guard_state == stack_guard_unused) return; aoqi@0: address low_addr = stack_base() - stack_size(); aoqi@0: size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size(); aoqi@0: aoqi@0: if (os::allocate_stack_guard_pages()) { aoqi@0: if (os::remove_stack_guard_pages((char *) low_addr, len)) { aoqi@0: _stack_guard_state = stack_guard_unused; aoqi@0: } else { aoqi@0: warning("Attempt to deallocate stack guard pages failed."); aoqi@0: } aoqi@0: } else { aoqi@0: if (_stack_guard_state == stack_guard_unused) return; aoqi@0: if (os::unguard_memory((char *) low_addr, len)) { aoqi@0: _stack_guard_state = stack_guard_unused; aoqi@0: } else { aoqi@0: warning("Attempt to unprotect stack guard pages failed."); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void JavaThread::enable_stack_yellow_zone() { aoqi@0: assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); aoqi@0: assert(_stack_guard_state != stack_guard_enabled, "already enabled"); aoqi@0: aoqi@0: // The base notation is from the stacks point of view, growing downward. aoqi@0: // We need to adjust it to work correctly with guard_memory() aoqi@0: address base = stack_yellow_zone_base() - stack_yellow_zone_size(); aoqi@0: aoqi@0: guarantee(base < stack_base(),"Error calculating stack yellow zone"); aoqi@0: guarantee(base < os::current_stack_pointer(),"Error calculating stack yellow zone"); aoqi@0: aoqi@0: if (os::guard_memory((char *) base, stack_yellow_zone_size())) { aoqi@0: _stack_guard_state = stack_guard_enabled; aoqi@0: } else { aoqi@0: warning("Attempt to guard stack yellow zone failed."); aoqi@0: } aoqi@0: enable_register_stack_guard(); aoqi@0: } aoqi@0: aoqi@0: void JavaThread::disable_stack_yellow_zone() { aoqi@0: assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); aoqi@0: assert(_stack_guard_state != stack_guard_yellow_disabled, "already disabled"); aoqi@0: aoqi@0: // Simply return if called for a thread that does not use guard pages. aoqi@0: if (_stack_guard_state == stack_guard_unused) return; aoqi@0: aoqi@0: // The base notation is from the stacks point of view, growing downward. aoqi@0: // We need to adjust it to work correctly with guard_memory() aoqi@0: address base = stack_yellow_zone_base() - stack_yellow_zone_size(); aoqi@0: aoqi@0: if (os::unguard_memory((char *)base, stack_yellow_zone_size())) { aoqi@0: _stack_guard_state = stack_guard_yellow_disabled; aoqi@0: } else { aoqi@0: warning("Attempt to unguard stack yellow zone failed."); aoqi@0: } aoqi@0: disable_register_stack_guard(); aoqi@0: } aoqi@0: aoqi@0: void JavaThread::enable_stack_red_zone() { aoqi@0: // The base notation is from the stacks point of view, growing downward. aoqi@0: // We need to adjust it to work correctly with guard_memory() aoqi@0: assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); aoqi@0: address base = stack_red_zone_base() - stack_red_zone_size(); aoqi@0: aoqi@0: guarantee(base < stack_base(),"Error calculating stack red zone"); aoqi@0: guarantee(base < os::current_stack_pointer(),"Error calculating stack red zone"); aoqi@0: aoqi@0: if(!os::guard_memory((char *) base, stack_red_zone_size())) { aoqi@0: warning("Attempt to guard stack red zone failed."); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void JavaThread::disable_stack_red_zone() { aoqi@0: // The base notation is from the stacks point of view, growing downward. aoqi@0: // We need to adjust it to work correctly with guard_memory() aoqi@0: assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); aoqi@0: address base = stack_red_zone_base() - stack_red_zone_size(); aoqi@0: if (!os::unguard_memory((char *)base, stack_red_zone_size())) { aoqi@0: warning("Attempt to unguard stack red zone failed."); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) { aoqi@0: // ignore is there is no stack aoqi@0: if (!has_last_Java_frame()) return; aoqi@0: // traverse the stack frames. Starts from top frame. aoqi@0: for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { aoqi@0: frame* fr = fst.current(); aoqi@0: f(fr, fst.register_map()); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: // Deoptimization aoqi@0: // Function for testing deoptimization aoqi@0: void JavaThread::deoptimize() { aoqi@0: // BiasedLocking needs an updated RegisterMap for the revoke monitors pass aoqi@0: StackFrameStream fst(this, UseBiasedLocking); aoqi@0: bool deopt = false; // Dump stack only if a deopt actually happens. aoqi@0: bool only_at = strlen(DeoptimizeOnlyAt) > 0; aoqi@0: // Iterate over all frames in the thread and deoptimize aoqi@0: for(; !fst.is_done(); fst.next()) { aoqi@0: if(fst.current()->can_be_deoptimized()) { aoqi@0: aoqi@0: if (only_at) { aoqi@0: // Deoptimize only at particular bcis. DeoptimizeOnlyAt aoqi@0: // consists of comma or carriage return separated numbers so aoqi@0: // search for the current bci in that string. aoqi@0: address pc = fst.current()->pc(); aoqi@0: nmethod* nm = (nmethod*) fst.current()->cb(); aoqi@0: ScopeDesc* sd = nm->scope_desc_at( pc); aoqi@0: char buffer[8]; aoqi@0: jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci()); aoqi@0: size_t len = strlen(buffer); aoqi@0: const char * found = strstr(DeoptimizeOnlyAt, buffer); aoqi@0: while (found != NULL) { aoqi@0: if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') && aoqi@0: (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) { aoqi@0: // Check that the bci found is bracketed by terminators. aoqi@0: break; aoqi@0: } aoqi@0: found = strstr(found + 1, buffer); aoqi@0: } aoqi@0: if (!found) { aoqi@0: continue; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (DebugDeoptimization && !deopt) { aoqi@0: deopt = true; // One-time only print before deopt aoqi@0: tty->print_cr("[BEFORE Deoptimization]"); aoqi@0: trace_frames(); aoqi@0: trace_stack(); aoqi@0: } aoqi@0: Deoptimization::deoptimize(this, *fst.current(), fst.register_map()); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (DebugDeoptimization && deopt) { aoqi@0: tty->print_cr("[AFTER Deoptimization]"); aoqi@0: trace_frames(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // Make zombies aoqi@0: void JavaThread::make_zombies() { aoqi@0: for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { aoqi@0: if (fst.current()->can_be_deoptimized()) { aoqi@0: // it is a Java nmethod aoqi@0: nmethod* nm = CodeCache::find_nmethod(fst.current()->pc()); aoqi@0: nm->make_not_entrant(); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: #endif // PRODUCT aoqi@0: aoqi@0: aoqi@0: void JavaThread::deoptimized_wrt_marked_nmethods() { aoqi@0: if (!has_last_Java_frame()) return; aoqi@0: // BiasedLocking needs an updated RegisterMap for the revoke monitors pass aoqi@0: StackFrameStream fst(this, UseBiasedLocking); aoqi@0: for(; !fst.is_done(); fst.next()) { aoqi@0: if (fst.current()->should_be_deoptimized()) { aoqi@0: if (LogCompilation && xtty != NULL) { aoqi@0: nmethod* nm = fst.current()->cb()->as_nmethod_or_null(); aoqi@0: xtty->elem("deoptimized thread='" UINTX_FORMAT "' compile_id='%d'", aoqi@0: this->name(), nm != NULL ? nm->compile_id() : -1); aoqi@0: } aoqi@0: aoqi@0: Deoptimization::deoptimize(this, *fst.current(), fst.register_map()); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // GC support aoqi@0: static void frame_gc_epilogue(frame* f, const RegisterMap* map) { f->gc_epilogue(); } aoqi@0: aoqi@0: void JavaThread::gc_epilogue() { aoqi@0: frames_do(frame_gc_epilogue); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: static void frame_gc_prologue(frame* f, const RegisterMap* map) { f->gc_prologue(); } aoqi@0: aoqi@0: void JavaThread::gc_prologue() { aoqi@0: frames_do(frame_gc_prologue); aoqi@0: } aoqi@0: aoqi@0: // If the caller is a NamedThread, then remember, in the current scope, aoqi@0: // the given JavaThread in its _processed_thread field. aoqi@0: class RememberProcessedThread: public StackObj { aoqi@0: NamedThread* _cur_thr; aoqi@0: public: aoqi@0: RememberProcessedThread(JavaThread* jthr) { aoqi@0: Thread* thread = Thread::current(); aoqi@0: if (thread->is_Named_thread()) { aoqi@0: _cur_thr = (NamedThread *)thread; aoqi@0: _cur_thr->set_processed_thread(jthr); aoqi@0: } else { aoqi@0: _cur_thr = NULL; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: ~RememberProcessedThread() { aoqi@0: if (_cur_thr) { aoqi@0: _cur_thr->set_processed_thread(NULL); aoqi@0: } aoqi@0: } aoqi@0: }; aoqi@0: aoqi@0: void JavaThread::oops_do(OopClosure* f, CLDToOopClosure* cld_f, CodeBlobClosure* cf) { aoqi@0: // Verify that the deferred card marks have been flushed. aoqi@0: assert(deferred_card_mark().is_empty(), "Should be empty during GC"); aoqi@0: aoqi@0: // The ThreadProfiler oops_do is done from FlatProfiler::oops_do aoqi@0: // since there may be more than one thread using each ThreadProfiler. aoqi@0: aoqi@0: // Traverse the GCHandles aoqi@0: Thread::oops_do(f, cld_f, cf); aoqi@0: aoqi@0: assert( (!has_last_Java_frame() && java_call_counter() == 0) || aoqi@0: (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); aoqi@0: aoqi@0: if (has_last_Java_frame()) { aoqi@0: // Record JavaThread to GC thread aoqi@0: RememberProcessedThread rpt(this); aoqi@0: aoqi@0: // Traverse the privileged stack aoqi@0: if (_privileged_stack_top != NULL) { aoqi@0: _privileged_stack_top->oops_do(f); aoqi@0: } aoqi@0: aoqi@0: // traverse the registered growable array aoqi@0: if (_array_for_gc != NULL) { aoqi@0: for (int index = 0; index < _array_for_gc->length(); index++) { aoqi@0: f->do_oop(_array_for_gc->adr_at(index)); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Traverse the monitor chunks aoqi@0: for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { aoqi@0: chunk->oops_do(f); aoqi@0: } aoqi@0: aoqi@0: // Traverse the execution stack aoqi@0: for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { aoqi@0: fst.current()->oops_do(f, cld_f, cf, fst.register_map()); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // callee_target is never live across a gc point so NULL it here should aoqi@0: // it still contain a methdOop. aoqi@0: aoqi@0: set_callee_target(NULL); aoqi@0: aoqi@0: assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!"); aoqi@0: // If we have deferred set_locals there might be oops waiting to be aoqi@0: // written aoqi@0: GrowableArray* list = deferred_locals(); aoqi@0: if (list != NULL) { aoqi@0: for (int i = 0; i < list->length(); i++) { aoqi@0: list->at(i)->oops_do(f); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Traverse instance variables at the end since the GC may be moving things aoqi@0: // around using this function aoqi@0: f->do_oop((oop*) &_threadObj); aoqi@0: f->do_oop((oop*) &_vm_result); aoqi@0: f->do_oop((oop*) &_exception_oop); aoqi@0: f->do_oop((oop*) &_pending_async_exception); aoqi@0: aoqi@0: if (jvmti_thread_state() != NULL) { aoqi@0: jvmti_thread_state()->oops_do(f); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void JavaThread::nmethods_do(CodeBlobClosure* cf) { aoqi@0: Thread::nmethods_do(cf); // (super method is a no-op) aoqi@0: aoqi@0: assert( (!has_last_Java_frame() && java_call_counter() == 0) || aoqi@0: (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); aoqi@0: aoqi@0: if (has_last_Java_frame()) { aoqi@0: // Traverse the execution stack aoqi@0: for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { aoqi@0: fst.current()->nmethods_do(cf); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void JavaThread::metadata_do(void f(Metadata*)) { aoqi@0: Thread::metadata_do(f); aoqi@0: if (has_last_Java_frame()) { aoqi@0: // Traverse the execution stack to call f() on the methods in the stack aoqi@0: for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { aoqi@0: fst.current()->metadata_do(f); aoqi@0: } aoqi@0: } else if (is_Compiler_thread()) { aoqi@0: // need to walk ciMetadata in current compile tasks to keep alive. aoqi@0: CompilerThread* ct = (CompilerThread*)this; aoqi@0: if (ct->env() != NULL) { aoqi@0: ct->env()->metadata_do(f); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Printing aoqi@0: const char* _get_thread_state_name(JavaThreadState _thread_state) { aoqi@0: switch (_thread_state) { aoqi@0: case _thread_uninitialized: return "_thread_uninitialized"; aoqi@0: case _thread_new: return "_thread_new"; aoqi@0: case _thread_new_trans: return "_thread_new_trans"; aoqi@0: case _thread_in_native: return "_thread_in_native"; aoqi@0: case _thread_in_native_trans: return "_thread_in_native_trans"; aoqi@0: case _thread_in_vm: return "_thread_in_vm"; aoqi@0: case _thread_in_vm_trans: return "_thread_in_vm_trans"; aoqi@0: case _thread_in_Java: return "_thread_in_Java"; aoqi@0: case _thread_in_Java_trans: return "_thread_in_Java_trans"; aoqi@0: case _thread_blocked: return "_thread_blocked"; aoqi@0: case _thread_blocked_trans: return "_thread_blocked_trans"; aoqi@0: default: return "unknown thread state"; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: void JavaThread::print_thread_state_on(outputStream *st) const { aoqi@0: st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state)); aoqi@0: }; aoqi@0: void JavaThread::print_thread_state() const { aoqi@0: print_thread_state_on(tty); aoqi@0: }; aoqi@0: #endif // PRODUCT aoqi@0: aoqi@0: // Called by Threads::print() for VM_PrintThreads operation aoqi@0: void JavaThread::print_on(outputStream *st) const { aoqi@0: st->print("\"%s\" ", get_thread_name()); aoqi@0: oop thread_oop = threadObj(); aoqi@0: if (thread_oop != NULL) { aoqi@0: st->print("#" INT64_FORMAT " ", java_lang_Thread::thread_id(thread_oop)); aoqi@0: if (java_lang_Thread::is_daemon(thread_oop)) st->print("daemon "); aoqi@0: st->print("prio=%d ", java_lang_Thread::priority(thread_oop)); aoqi@0: } aoqi@0: Thread::print_on(st); aoqi@0: // print guess for valid stack memory region (assume 4K pages); helps lock debugging aoqi@0: st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12)); aoqi@0: if (thread_oop != NULL && JDK_Version::is_gte_jdk15x_version()) { aoqi@0: st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop)); aoqi@0: } aoqi@0: #ifndef PRODUCT aoqi@0: print_thread_state_on(st); aoqi@0: _safepoint_state->print_on(st); aoqi@0: #endif // PRODUCT aoqi@0: } aoqi@0: aoqi@0: // Called by fatal error handler. The difference between this and aoqi@0: // JavaThread::print() is that we can't grab lock or allocate memory. aoqi@0: void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const { aoqi@0: st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen)); aoqi@0: oop thread_obj = threadObj(); aoqi@0: if (thread_obj != NULL) { aoqi@0: if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon"); aoqi@0: } aoqi@0: st->print(" ["); aoqi@0: st->print("%s", _get_thread_state_name(_thread_state)); aoqi@0: if (osthread()) { aoqi@0: st->print(", id=%d", osthread()->thread_id()); aoqi@0: } aoqi@0: st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")", aoqi@0: _stack_base - _stack_size, _stack_base); aoqi@0: st->print("]"); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: // Verification aoqi@0: aoqi@0: static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); } aoqi@0: aoqi@0: void JavaThread::verify() { aoqi@0: // Verify oops in the thread. aoqi@0: oops_do(&VerifyOopClosure::verify_oop, NULL, NULL); aoqi@0: aoqi@0: // Verify the stack frames. aoqi@0: frames_do(frame_verify); aoqi@0: } aoqi@0: aoqi@0: // CR 6300358 (sub-CR 2137150) aoqi@0: // Most callers of this method assume that it can't return NULL but a aoqi@0: // thread may not have a name whilst it is in the process of attaching to aoqi@0: // the VM - see CR 6412693, and there are places where a JavaThread can be aoqi@0: // seen prior to having it's threadObj set (eg JNI attaching threads and aoqi@0: // if vm exit occurs during initialization). These cases can all be accounted aoqi@0: // for such that this method never returns NULL. aoqi@0: const char* JavaThread::get_thread_name() const { aoqi@0: #ifdef ASSERT aoqi@0: // early safepoints can hit while current thread does not yet have TLS aoqi@0: if (!SafepointSynchronize::is_at_safepoint()) { aoqi@0: Thread *cur = Thread::current(); aoqi@0: if (!(cur->is_Java_thread() && cur == this)) { aoqi@0: // Current JavaThreads are allowed to get their own name without aoqi@0: // the Threads_lock. aoqi@0: assert_locked_or_safepoint(Threads_lock); aoqi@0: } aoqi@0: } aoqi@0: #endif // ASSERT aoqi@0: return get_thread_name_string(); aoqi@0: } aoqi@0: aoqi@0: // Returns a non-NULL representation of this thread's name, or a suitable aoqi@0: // descriptive string if there is no set name aoqi@0: const char* JavaThread::get_thread_name_string(char* buf, int buflen) const { aoqi@0: const char* name_str; aoqi@0: oop thread_obj = threadObj(); aoqi@0: if (thread_obj != NULL) { aoqi@0: typeArrayOop name = java_lang_Thread::name(thread_obj); aoqi@0: if (name != NULL) { aoqi@0: if (buf == NULL) { aoqi@0: name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length()); aoqi@0: } aoqi@0: else { aoqi@0: name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length(), buf, buflen); aoqi@0: } aoqi@0: } aoqi@0: else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306 aoqi@0: name_str = ""; aoqi@0: } aoqi@0: else { aoqi@0: name_str = Thread::name(); aoqi@0: } aoqi@0: } aoqi@0: else { aoqi@0: name_str = Thread::name(); aoqi@0: } aoqi@0: assert(name_str != NULL, "unexpected NULL thread name"); aoqi@0: return name_str; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: const char* JavaThread::get_threadgroup_name() const { aoqi@0: debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);) aoqi@0: oop thread_obj = threadObj(); aoqi@0: if (thread_obj != NULL) { aoqi@0: oop thread_group = java_lang_Thread::threadGroup(thread_obj); aoqi@0: if (thread_group != NULL) { aoqi@0: typeArrayOop name = java_lang_ThreadGroup::name(thread_group); aoqi@0: // ThreadGroup.name can be null aoqi@0: if (name != NULL) { aoqi@0: const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length()); aoqi@0: return str; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: return NULL; aoqi@0: } aoqi@0: aoqi@0: const char* JavaThread::get_parent_name() const { aoqi@0: debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);) aoqi@0: oop thread_obj = threadObj(); aoqi@0: if (thread_obj != NULL) { aoqi@0: oop thread_group = java_lang_Thread::threadGroup(thread_obj); aoqi@0: if (thread_group != NULL) { aoqi@0: oop parent = java_lang_ThreadGroup::parent(thread_group); aoqi@0: if (parent != NULL) { aoqi@0: typeArrayOop name = java_lang_ThreadGroup::name(parent); aoqi@0: // ThreadGroup.name can be null aoqi@0: if (name != NULL) { aoqi@0: const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length()); aoqi@0: return str; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: return NULL; aoqi@0: } aoqi@0: aoqi@0: ThreadPriority JavaThread::java_priority() const { aoqi@0: oop thr_oop = threadObj(); aoqi@0: if (thr_oop == NULL) return NormPriority; // Bootstrapping aoqi@0: ThreadPriority priority = java_lang_Thread::priority(thr_oop); aoqi@0: assert(MinPriority <= priority && priority <= MaxPriority, "sanity check"); aoqi@0: return priority; aoqi@0: } aoqi@0: aoqi@0: void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) { aoqi@0: aoqi@0: assert(Threads_lock->owner() == Thread::current(), "must have threads lock"); aoqi@0: // Link Java Thread object <-> C++ Thread aoqi@0: aoqi@0: // Get the C++ thread object (an oop) from the JNI handle (a jthread) aoqi@0: // and put it into a new Handle. The Handle "thread_oop" can then aoqi@0: // be used to pass the C++ thread object to other methods. aoqi@0: aoqi@0: // Set the Java level thread object (jthread) field of the aoqi@0: // new thread (a JavaThread *) to C++ thread object using the aoqi@0: // "thread_oop" handle. aoqi@0: aoqi@0: // Set the thread field (a JavaThread *) of the aoqi@0: // oop representing the java_lang_Thread to the new thread (a JavaThread *). aoqi@0: aoqi@0: Handle thread_oop(Thread::current(), aoqi@0: JNIHandles::resolve_non_null(jni_thread)); aoqi@0: assert(InstanceKlass::cast(thread_oop->klass())->is_linked(), aoqi@0: "must be initialized"); aoqi@0: set_threadObj(thread_oop()); aoqi@0: java_lang_Thread::set_thread(thread_oop(), this); aoqi@0: aoqi@0: if (prio == NoPriority) { aoqi@0: prio = java_lang_Thread::priority(thread_oop()); aoqi@0: assert(prio != NoPriority, "A valid priority should be present"); aoqi@0: } aoqi@0: aoqi@0: // Push the Java priority down to the native thread; needs Threads_lock aoqi@0: Thread::set_priority(this, prio); aoqi@0: aoqi@0: // Add the new thread to the Threads list and set it in motion. aoqi@0: // We must have threads lock in order to call Threads::add. aoqi@0: // It is crucial that we do not block before the thread is aoqi@0: // added to the Threads list for if a GC happens, then the java_thread oop aoqi@0: // will not be visited by GC. aoqi@0: Threads::add(this); aoqi@0: } aoqi@0: aoqi@0: oop JavaThread::current_park_blocker() { aoqi@0: // Support for JSR-166 locks aoqi@0: oop thread_oop = threadObj(); aoqi@0: if (thread_oop != NULL && aoqi@0: JDK_Version::current().supports_thread_park_blocker()) { aoqi@0: return java_lang_Thread::park_blocker(thread_oop); aoqi@0: } aoqi@0: return NULL; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void JavaThread::print_stack_on(outputStream* st) { aoqi@0: if (!has_last_Java_frame()) return; aoqi@0: ResourceMark rm; aoqi@0: HandleMark hm; aoqi@0: aoqi@0: RegisterMap reg_map(this); aoqi@0: vframe* start_vf = last_java_vframe(®_map); aoqi@0: int count = 0; aoqi@0: for (vframe* f = start_vf; f; f = f->sender() ) { aoqi@0: if (f->is_java_frame()) { aoqi@0: javaVFrame* jvf = javaVFrame::cast(f); aoqi@0: java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci()); aoqi@0: aoqi@0: // Print out lock information aoqi@0: if (JavaMonitorsInStackTrace) { aoqi@0: jvf->print_lock_info_on(st, count); aoqi@0: } aoqi@0: } else { aoqi@0: // Ignore non-Java frames aoqi@0: } aoqi@0: aoqi@0: // Bail-out case for too deep stacks aoqi@0: count++; aoqi@0: if (MaxJavaStackTraceDepth == count) return; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // JVMTI PopFrame support aoqi@0: void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) { aoqi@0: assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments"); aoqi@0: if (in_bytes(size_in_bytes) != 0) { aoqi@0: _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread); aoqi@0: _popframe_preserved_args_size = in_bytes(size_in_bytes); aoqi@0: Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void* JavaThread::popframe_preserved_args() { aoqi@0: return _popframe_preserved_args; aoqi@0: } aoqi@0: aoqi@0: ByteSize JavaThread::popframe_preserved_args_size() { aoqi@0: return in_ByteSize(_popframe_preserved_args_size); aoqi@0: } aoqi@0: aoqi@0: WordSize JavaThread::popframe_preserved_args_size_in_words() { aoqi@0: int sz = in_bytes(popframe_preserved_args_size()); aoqi@0: assert(sz % wordSize == 0, "argument size must be multiple of wordSize"); aoqi@0: return in_WordSize(sz / wordSize); aoqi@0: } aoqi@0: aoqi@0: void JavaThread::popframe_free_preserved_args() { aoqi@0: assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice"); aoqi@0: FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args, mtThread); aoqi@0: _popframe_preserved_args = NULL; aoqi@0: _popframe_preserved_args_size = 0; aoqi@0: } aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: aoqi@0: void JavaThread::trace_frames() { aoqi@0: tty->print_cr("[Describe stack]"); aoqi@0: int frame_no = 1; aoqi@0: for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { aoqi@0: tty->print(" %d. ", frame_no++); aoqi@0: fst.current()->print_value_on(tty,this); aoqi@0: tty->cr(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: class PrintAndVerifyOopClosure: public OopClosure { aoqi@0: protected: aoqi@0: template inline void do_oop_work(T* p) { aoqi@0: oop obj = oopDesc::load_decode_heap_oop(p); aoqi@0: if (obj == NULL) return; aoqi@0: tty->print(INTPTR_FORMAT ": ", p); aoqi@0: if (obj->is_oop_or_null()) { aoqi@0: if (obj->is_objArray()) { aoqi@0: tty->print_cr("valid objArray: " INTPTR_FORMAT, (oopDesc*) obj); aoqi@0: } else { aoqi@0: obj->print(); aoqi@0: } aoqi@0: } else { aoqi@0: tty->print_cr("invalid oop: " INTPTR_FORMAT, (oopDesc*) obj); aoqi@0: } aoqi@0: tty->cr(); aoqi@0: } aoqi@0: public: aoqi@0: virtual void do_oop(oop* p) { do_oop_work(p); } aoqi@0: virtual void do_oop(narrowOop* p) { do_oop_work(p); } aoqi@0: }; aoqi@0: aoqi@0: aoqi@0: static void oops_print(frame* f, const RegisterMap *map) { aoqi@0: PrintAndVerifyOopClosure print; aoqi@0: f->print_value(); aoqi@0: f->oops_do(&print, NULL, NULL, (RegisterMap*)map); aoqi@0: } aoqi@0: aoqi@0: // Print our all the locations that contain oops and whether they are aoqi@0: // valid or not. This useful when trying to find the oldest frame aoqi@0: // where an oop has gone bad since the frame walk is from youngest to aoqi@0: // oldest. aoqi@0: void JavaThread::trace_oops() { aoqi@0: tty->print_cr("[Trace oops]"); aoqi@0: frames_do(oops_print); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: #ifdef ASSERT aoqi@0: // Print or validate the layout of stack frames aoqi@0: void JavaThread::print_frame_layout(int depth, bool validate_only) { aoqi@0: ResourceMark rm; aoqi@0: PRESERVE_EXCEPTION_MARK; aoqi@0: FrameValues values; aoqi@0: int frame_no = 0; aoqi@0: for(StackFrameStream fst(this, false); !fst.is_done(); fst.next()) { aoqi@0: fst.current()->describe(values, ++frame_no); aoqi@0: if (depth == frame_no) break; aoqi@0: } aoqi@0: if (validate_only) { aoqi@0: values.validate(); aoqi@0: } else { aoqi@0: tty->print_cr("[Describe stack layout]"); aoqi@0: values.print(this); aoqi@0: } aoqi@0: } aoqi@0: #endif aoqi@0: aoqi@0: void JavaThread::trace_stack_from(vframe* start_vf) { aoqi@0: ResourceMark rm; aoqi@0: int vframe_no = 1; aoqi@0: for (vframe* f = start_vf; f; f = f->sender() ) { aoqi@0: if (f->is_java_frame()) { aoqi@0: javaVFrame::cast(f)->print_activation(vframe_no++); aoqi@0: } else { aoqi@0: f->print(); aoqi@0: } aoqi@0: if (vframe_no > StackPrintLimit) { aoqi@0: tty->print_cr("......"); aoqi@0: return; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void JavaThread::trace_stack() { aoqi@0: if (!has_last_Java_frame()) return; aoqi@0: ResourceMark rm; aoqi@0: HandleMark hm; aoqi@0: RegisterMap reg_map(this); aoqi@0: trace_stack_from(last_java_vframe(®_map)); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: #endif // PRODUCT aoqi@0: aoqi@0: aoqi@0: javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) { aoqi@0: assert(reg_map != NULL, "a map must be given"); aoqi@0: frame f = last_frame(); aoqi@0: for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender() ) { aoqi@0: if (vf->is_java_frame()) return javaVFrame::cast(vf); aoqi@0: } aoqi@0: return NULL; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: Klass* JavaThread::security_get_caller_class(int depth) { aoqi@0: vframeStream vfst(this); aoqi@0: vfst.security_get_caller_frame(depth); aoqi@0: if (!vfst.at_end()) { aoqi@0: return vfst.method()->method_holder(); aoqi@0: } aoqi@0: return NULL; aoqi@0: } aoqi@0: aoqi@0: static void compiler_thread_entry(JavaThread* thread, TRAPS) { aoqi@0: assert(thread->is_Compiler_thread(), "must be compiler thread"); aoqi@0: CompileBroker::compiler_thread_loop(); aoqi@0: } aoqi@0: aoqi@0: // Create a CompilerThread aoqi@0: CompilerThread::CompilerThread(CompileQueue* queue, CompilerCounters* counters) aoqi@0: : JavaThread(&compiler_thread_entry) { aoqi@0: _env = NULL; aoqi@0: _log = NULL; aoqi@0: _task = NULL; aoqi@0: _queue = queue; aoqi@0: _counters = counters; aoqi@0: _buffer_blob = NULL; aoqi@0: _scanned_nmethod = NULL; aoqi@0: _compiler = NULL; aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: _ideal_graph_printer = NULL; aoqi@0: #endif aoqi@0: } aoqi@0: aoqi@0: void CompilerThread::oops_do(OopClosure* f, CLDToOopClosure* cld_f, CodeBlobClosure* cf) { aoqi@0: JavaThread::oops_do(f, cld_f, cf); aoqi@0: if (_scanned_nmethod != NULL && cf != NULL) { aoqi@0: // Safepoints can occur when the sweeper is scanning an nmethod so aoqi@0: // process it here to make sure it isn't unloaded in the middle of aoqi@0: // a scan. aoqi@0: cf->do_code_blob(_scanned_nmethod); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // ======= Threads ======== aoqi@0: aoqi@0: // The Threads class links together all active threads, and provides aoqi@0: // operations over all threads. It is protected by its own Mutex aoqi@0: // lock, which is also used in other contexts to protect thread aoqi@0: // operations from having the thread being operated on from exiting aoqi@0: // and going away unexpectedly (e.g., safepoint synchronization) aoqi@0: aoqi@0: JavaThread* Threads::_thread_list = NULL; aoqi@0: int Threads::_number_of_threads = 0; aoqi@0: int Threads::_number_of_non_daemon_threads = 0; aoqi@0: int Threads::_return_code = 0; aoqi@0: size_t JavaThread::_stack_size_at_create = 0; aoqi@0: #ifdef ASSERT aoqi@0: bool Threads::_vm_complete = false; aoqi@0: #endif aoqi@0: aoqi@0: // All JavaThreads aoqi@0: #define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next()) aoqi@0: aoqi@0: // All JavaThreads + all non-JavaThreads (i.e., every thread in the system) aoqi@0: void Threads::threads_do(ThreadClosure* tc) { aoqi@0: assert_locked_or_safepoint(Threads_lock); aoqi@0: // ALL_JAVA_THREADS iterates through all JavaThreads aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: tc->do_thread(p); aoqi@0: } aoqi@0: // Someday we could have a table or list of all non-JavaThreads. aoqi@0: // For now, just manually iterate through them. aoqi@0: tc->do_thread(VMThread::vm_thread()); aoqi@0: Universe::heap()->gc_threads_do(tc); aoqi@0: WatcherThread *wt = WatcherThread::watcher_thread(); aoqi@0: // Strictly speaking, the following NULL check isn't sufficient to make sure aoqi@0: // the data for WatcherThread is still valid upon being examined. However, aoqi@0: // considering that WatchThread terminates when the VM is on the way to aoqi@0: // exit at safepoint, the chance of the above is extremely small. The right aoqi@0: // way to prevent termination of WatcherThread would be to acquire aoqi@0: // Terminator_lock, but we can't do that without violating the lock rank aoqi@0: // checking in some cases. aoqi@0: if (wt != NULL) aoqi@0: tc->do_thread(wt); aoqi@0: aoqi@0: // If CompilerThreads ever become non-JavaThreads, add them here aoqi@0: } aoqi@0: aoqi@0: jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { aoqi@0: aoqi@0: extern void JDK_Version_init(); aoqi@0: aoqi@0: // Check version aoqi@0: if (!is_supported_jni_version(args->version)) return JNI_EVERSION; aoqi@0: aoqi@0: // Initialize the output stream module aoqi@0: ostream_init(); aoqi@0: aoqi@0: // Process java launcher properties. aoqi@0: Arguments::process_sun_java_launcher_properties(args); aoqi@0: aoqi@0: // Initialize the os module before using TLS aoqi@0: os::init(); aoqi@0: aoqi@0: // Initialize system properties. aoqi@0: Arguments::init_system_properties(); aoqi@0: aoqi@0: // So that JDK version can be used as a discrimintor when parsing arguments aoqi@0: JDK_Version_init(); aoqi@0: aoqi@0: // Update/Initialize System properties after JDK version number is known aoqi@0: Arguments::init_version_specific_system_properties(); aoqi@0: aoqi@0: // Parse arguments aoqi@0: jint parse_result = Arguments::parse(args); aoqi@0: if (parse_result != JNI_OK) return parse_result; aoqi@0: aoqi@0: os::init_before_ergo(); aoqi@0: aoqi@0: jint ergo_result = Arguments::apply_ergo(); aoqi@0: if (ergo_result != JNI_OK) return ergo_result; aoqi@0: aoqi@0: if (PauseAtStartup) { aoqi@0: os::pause(); aoqi@0: } aoqi@0: aoqi@0: #ifndef USDT2 aoqi@0: HS_DTRACE_PROBE(hotspot, vm__init__begin); aoqi@0: #else /* USDT2 */ aoqi@0: HOTSPOT_VM_INIT_BEGIN(); aoqi@0: #endif /* USDT2 */ aoqi@0: aoqi@0: // Record VM creation timing statistics aoqi@0: TraceVmCreationTime create_vm_timer; aoqi@0: create_vm_timer.start(); aoqi@0: aoqi@0: // Timing (must come after argument parsing) aoqi@0: TraceTime timer("Create VM", TraceStartupTime); aoqi@0: aoqi@0: // Initialize the os module after parsing the args aoqi@0: jint os_init_2_result = os::init_2(); aoqi@0: if (os_init_2_result != JNI_OK) return os_init_2_result; aoqi@0: aoqi@0: jint adjust_after_os_result = Arguments::adjust_after_os(); aoqi@0: if (adjust_after_os_result != JNI_OK) return adjust_after_os_result; aoqi@0: aoqi@0: // intialize TLS aoqi@0: ThreadLocalStorage::init(); aoqi@0: aoqi@0: // Bootstrap native memory tracking, so it can start recording memory aoqi@0: // activities before worker thread is started. This is the first phase aoqi@0: // of bootstrapping, VM is currently running in single-thread mode. aoqi@0: MemTracker::bootstrap_single_thread(); aoqi@0: aoqi@0: // Initialize output stream logging aoqi@0: ostream_init_log(); aoqi@0: aoqi@0: // Convert -Xrun to -agentlib: if there is no JVM_OnLoad aoqi@0: // Must be before create_vm_init_agents() aoqi@0: if (Arguments::init_libraries_at_startup()) { aoqi@0: convert_vm_init_libraries_to_agents(); aoqi@0: } aoqi@0: aoqi@0: // Launch -agentlib/-agentpath and converted -Xrun agents aoqi@0: if (Arguments::init_agents_at_startup()) { aoqi@0: create_vm_init_agents(); aoqi@0: } aoqi@0: aoqi@0: // Initialize Threads state aoqi@0: _thread_list = NULL; aoqi@0: _number_of_threads = 0; aoqi@0: _number_of_non_daemon_threads = 0; aoqi@0: aoqi@0: // Initialize global data structures and create system classes in heap aoqi@0: vm_init_globals(); aoqi@0: aoqi@0: // Attach the main thread to this os thread aoqi@0: JavaThread* main_thread = new JavaThread(); aoqi@0: main_thread->set_thread_state(_thread_in_vm); aoqi@0: // must do this before set_active_handles and initialize_thread_local_storage aoqi@0: // Note: on solaris initialize_thread_local_storage() will (indirectly) aoqi@0: // change the stack size recorded here to one based on the java thread aoqi@0: // stacksize. This adjusted size is what is used to figure the placement aoqi@0: // of the guard pages. aoqi@0: main_thread->record_stack_base_and_size(); aoqi@0: main_thread->initialize_thread_local_storage(); aoqi@0: aoqi@0: main_thread->set_active_handles(JNIHandleBlock::allocate_block()); aoqi@0: aoqi@0: if (!main_thread->set_as_starting_thread()) { aoqi@0: vm_shutdown_during_initialization( aoqi@0: "Failed necessary internal allocation. Out of swap space"); aoqi@0: delete main_thread; aoqi@0: *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again aoqi@0: return JNI_ENOMEM; aoqi@0: } aoqi@0: aoqi@0: // Enable guard page *after* os::create_main_thread(), otherwise it would aoqi@0: // crash Linux VM, see notes in os_linux.cpp. aoqi@0: main_thread->create_stack_guard_pages(); aoqi@0: aoqi@0: // Initialize Java-Level synchronization subsystem aoqi@0: ObjectMonitor::Initialize() ; aoqi@0: aoqi@0: // Second phase of bootstrapping, VM is about entering multi-thread mode aoqi@0: MemTracker::bootstrap_multi_thread(); aoqi@0: aoqi@0: // Initialize global modules aoqi@0: jint status = init_globals(); aoqi@0: if (status != JNI_OK) { aoqi@0: delete main_thread; aoqi@0: *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again aoqi@0: return status; aoqi@0: } aoqi@0: aoqi@0: // Should be done after the heap is fully created aoqi@0: main_thread->cache_global_variables(); aoqi@0: aoqi@0: HandleMark hm; aoqi@0: aoqi@0: { MutexLocker mu(Threads_lock); aoqi@0: Threads::add(main_thread); aoqi@0: } aoqi@0: aoqi@0: // Any JVMTI raw monitors entered in onload will transition into aoqi@0: // real raw monitor. VM is setup enough here for raw monitor enter. aoqi@0: JvmtiExport::transition_pending_onload_raw_monitors(); aoqi@0: aoqi@0: // Fully start NMT aoqi@0: MemTracker::start(); aoqi@0: aoqi@0: // Create the VMThread aoqi@0: { TraceTime timer("Start VMThread", TraceStartupTime); aoqi@0: VMThread::create(); aoqi@0: Thread* vmthread = VMThread::vm_thread(); aoqi@0: aoqi@0: if (!os::create_thread(vmthread, os::vm_thread)) aoqi@0: vm_exit_during_initialization("Cannot create VM thread. Out of system resources."); aoqi@0: aoqi@0: // Wait for the VM thread to become ready, and VMThread::run to initialize aoqi@0: // Monitors can have spurious returns, must always check another state flag aoqi@0: { aoqi@0: MutexLocker ml(Notify_lock); aoqi@0: os::start_thread(vmthread); aoqi@0: while (vmthread->active_handles() == NULL) { aoqi@0: Notify_lock->wait(); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: assert (Universe::is_fully_initialized(), "not initialized"); aoqi@0: if (VerifyDuringStartup) { aoqi@0: // Make sure we're starting with a clean slate. aoqi@0: VM_Verify verify_op; aoqi@0: VMThread::execute(&verify_op); aoqi@0: } aoqi@0: aoqi@0: EXCEPTION_MARK; aoqi@0: aoqi@0: // At this point, the Universe is initialized, but we have not executed aoqi@0: // any byte code. Now is a good time (the only time) to dump out the aoqi@0: // internal state of the JVM for sharing. aoqi@0: if (DumpSharedSpaces) { aoqi@0: MetaspaceShared::preload_and_dump(CHECK_0); aoqi@0: ShouldNotReachHere(); aoqi@0: } aoqi@0: aoqi@0: // Always call even when there are not JVMTI environments yet, since environments aoqi@0: // may be attached late and JVMTI must track phases of VM execution aoqi@0: JvmtiExport::enter_start_phase(); aoqi@0: aoqi@0: // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. aoqi@0: JvmtiExport::post_vm_start(); aoqi@0: aoqi@0: { aoqi@0: TraceTime timer("Initialize java.lang classes", TraceStartupTime); aoqi@0: aoqi@0: if (EagerXrunInit && Arguments::init_libraries_at_startup()) { aoqi@0: create_vm_init_libraries(); aoqi@0: } aoqi@0: aoqi@0: initialize_class(vmSymbols::java_lang_String(), CHECK_0); aoqi@0: aoqi@0: // Initialize java_lang.System (needed before creating the thread) aoqi@0: initialize_class(vmSymbols::java_lang_System(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0); aoqi@0: Handle thread_group = create_initial_thread_group(CHECK_0); aoqi@0: Universe::set_main_thread_group(thread_group()); aoqi@0: initialize_class(vmSymbols::java_lang_Thread(), CHECK_0); aoqi@0: oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0); aoqi@0: main_thread->set_threadObj(thread_object); aoqi@0: // Set thread status to running since main thread has aoqi@0: // been started and running. aoqi@0: java_lang_Thread::set_thread_status(thread_object, aoqi@0: java_lang_Thread::RUNNABLE); aoqi@0: aoqi@0: // The VM creates & returns objects of this class. Make sure it's initialized. aoqi@0: initialize_class(vmSymbols::java_lang_Class(), CHECK_0); aoqi@0: aoqi@0: // The VM preresolves methods to these classes. Make sure that they get initialized aoqi@0: initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK_0); aoqi@0: call_initializeSystemClass(CHECK_0); aoqi@0: aoqi@0: // get the Java runtime name after java.lang.System is initialized aoqi@0: JDK_Version::set_runtime_name(get_java_runtime_name(THREAD)); aoqi@0: JDK_Version::set_runtime_version(get_java_runtime_version(THREAD)); aoqi@0: aoqi@0: // an instance of OutOfMemory exception has been allocated earlier aoqi@0: initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK_0); aoqi@0: } aoqi@0: aoqi@0: // See : bugid 4211085. aoqi@0: // Background : the static initializer of java.lang.Compiler tries to read aoqi@0: // property"java.compiler" and read & write property "java.vm.info". aoqi@0: // When a security manager is installed through the command line aoqi@0: // option "-Djava.security.manager", the above properties are not aoqi@0: // readable and the static initializer for java.lang.Compiler fails aoqi@0: // resulting in a NoClassDefFoundError. This can happen in any aoqi@0: // user code which calls methods in java.lang.Compiler. aoqi@0: // Hack : the hack is to pre-load and initialize this class, so that only aoqi@0: // system domains are on the stack when the properties are read. aoqi@0: // Currently even the AWT code has calls to methods in java.lang.Compiler. aoqi@0: // On the classic VM, java.lang.Compiler is loaded very early to load the JIT. aoqi@0: // Future Fix : the best fix is to grant everyone permissions to read "java.compiler" and aoqi@0: // read and write"java.vm.info" in the default policy file. See bugid 4211383 aoqi@0: // Once that is done, we should remove this hack. aoqi@0: initialize_class(vmSymbols::java_lang_Compiler(), CHECK_0); aoqi@0: aoqi@0: // More hackery - the static initializer of java.lang.Compiler adds the string "nojit" to aoqi@0: // the java.vm.info property if no jit gets loaded through java.lang.Compiler (the hotspot aoqi@0: // compiler does not get loaded through java.lang.Compiler). "java -version" with the aoqi@0: // hotspot vm says "nojit" all the time which is confusing. So, we reset it here. aoqi@0: // This should also be taken out as soon as 4211383 gets fixed. aoqi@0: reset_vm_info_property(CHECK_0); aoqi@0: aoqi@0: quicken_jni_functions(); aoqi@0: aoqi@0: // Must be run after init_ft which initializes ft_enabled aoqi@0: if (TRACE_INITIALIZE() != JNI_OK) { aoqi@0: vm_exit_during_initialization("Failed to initialize tracing backend"); aoqi@0: } aoqi@0: aoqi@0: // Set flag that basic initialization has completed. Used by exceptions and various aoqi@0: // debug stuff, that does not work until all basic classes have been initialized. aoqi@0: set_init_completed(); aoqi@0: aoqi@0: Metaspace::post_initialize(); aoqi@0: aoqi@0: #ifndef USDT2 aoqi@0: HS_DTRACE_PROBE(hotspot, vm__init__end); aoqi@0: #else /* USDT2 */ aoqi@0: HOTSPOT_VM_INIT_END(); aoqi@0: #endif /* USDT2 */ aoqi@0: aoqi@0: // record VM initialization completion time aoqi@0: #if INCLUDE_MANAGEMENT aoqi@0: Management::record_vm_init_completed(); aoqi@0: #endif // INCLUDE_MANAGEMENT aoqi@0: aoqi@0: // Compute system loader. Note that this has to occur after set_init_completed, since aoqi@0: // valid exceptions may be thrown in the process. aoqi@0: // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and aoqi@0: // set_init_completed has just been called, causing exceptions not to be shortcut aoqi@0: // anymore. We call vm_exit_during_initialization directly instead. aoqi@0: SystemDictionary::compute_java_system_loader(THREAD); aoqi@0: if (HAS_PENDING_EXCEPTION) { aoqi@0: vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION)); aoqi@0: } aoqi@0: aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: // Support for ConcurrentMarkSweep. This should be cleaned up aoqi@0: // and better encapsulated. The ugly nested if test would go away aoqi@0: // once things are properly refactored. XXX YSR aoqi@0: if (UseConcMarkSweepGC || UseG1GC) { aoqi@0: if (UseConcMarkSweepGC) { aoqi@0: ConcurrentMarkSweepThread::makeSurrogateLockerThread(THREAD); aoqi@0: } else { aoqi@0: ConcurrentMarkThread::makeSurrogateLockerThread(THREAD); aoqi@0: } aoqi@0: if (HAS_PENDING_EXCEPTION) { aoqi@0: vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION)); aoqi@0: } aoqi@0: } aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: aoqi@0: // Always call even when there are not JVMTI environments yet, since environments aoqi@0: // may be attached late and JVMTI must track phases of VM execution aoqi@0: JvmtiExport::enter_live_phase(); aoqi@0: aoqi@0: // Signal Dispatcher needs to be started before VMInit event is posted aoqi@0: os::signal_init(); aoqi@0: aoqi@0: // Start Attach Listener if +StartAttachListener or it can't be started lazily aoqi@0: if (!DisableAttachMechanism) { aoqi@0: AttachListener::vm_start(); aoqi@0: if (StartAttachListener || AttachListener::init_at_startup()) { aoqi@0: AttachListener::init(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Launch -Xrun agents aoqi@0: // Must be done in the JVMTI live phase so that for backward compatibility the JDWP aoqi@0: // back-end can launch with -Xdebug -Xrunjdwp. aoqi@0: if (!EagerXrunInit && Arguments::init_libraries_at_startup()) { aoqi@0: create_vm_init_libraries(); aoqi@0: } aoqi@0: aoqi@0: // Notify JVMTI agents that VM initialization is complete - nop if no agents. aoqi@0: JvmtiExport::post_vm_initialized(); aoqi@0: aoqi@0: if (TRACE_START() != JNI_OK) { aoqi@0: vm_exit_during_initialization("Failed to start tracing backend."); aoqi@0: } aoqi@0: aoqi@0: if (CleanChunkPoolAsync) { aoqi@0: Chunk::start_chunk_pool_cleaner_task(); aoqi@0: } aoqi@0: aoqi@0: // initialize compiler(s) aoqi@0: #if defined(COMPILER1) || defined(COMPILER2) || defined(SHARK) aoqi@0: CompileBroker::compilation_init(); aoqi@0: #endif aoqi@0: aoqi@0: if (EnableInvokeDynamic) { aoqi@0: // Pre-initialize some JSR292 core classes to avoid deadlock during class loading. aoqi@0: // It is done after compilers are initialized, because otherwise compilations of aoqi@0: // signature polymorphic MH intrinsics can be missed aoqi@0: // (see SystemDictionary::find_method_handle_intrinsic). aoqi@0: initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK_0); aoqi@0: initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK_0); aoqi@0: } aoqi@0: aoqi@0: #if INCLUDE_MANAGEMENT aoqi@0: Management::initialize(THREAD); aoqi@0: #endif // INCLUDE_MANAGEMENT aoqi@0: aoqi@0: if (HAS_PENDING_EXCEPTION) { aoqi@0: // management agent fails to start possibly due to aoqi@0: // configuration problem and is responsible for printing aoqi@0: // stack trace if appropriate. Simply exit VM. aoqi@0: vm_exit(1); aoqi@0: } aoqi@0: aoqi@0: if (Arguments::has_profile()) FlatProfiler::engage(main_thread, true); aoqi@0: if (MemProfiling) MemProfiler::engage(); aoqi@0: StatSampler::engage(); aoqi@0: if (CheckJNICalls) JniPeriodicChecker::engage(); aoqi@0: aoqi@0: BiasedLocking::init(); aoqi@0: aoqi@0: #if INCLUDE_RTM_OPT aoqi@0: RTMLockingCounters::init(); aoqi@0: #endif aoqi@0: aoqi@0: if (JDK_Version::current().post_vm_init_hook_enabled()) { aoqi@0: call_postVMInitHook(THREAD); aoqi@0: // The Java side of PostVMInitHook.run must deal with all aoqi@0: // exceptions and provide means of diagnosis. aoqi@0: if (HAS_PENDING_EXCEPTION) { aoqi@0: CLEAR_PENDING_EXCEPTION; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: { aoqi@0: MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag); aoqi@0: // Make sure the watcher thread can be started by WatcherThread::start() aoqi@0: // or by dynamic enrollment. aoqi@0: WatcherThread::make_startable(); aoqi@0: // Start up the WatcherThread if there are any periodic tasks aoqi@0: // NOTE: All PeriodicTasks should be registered by now. If they aoqi@0: // aren't, late joiners might appear to start slowly (we might aoqi@0: // take a while to process their first tick). aoqi@0: if (PeriodicTask::num_tasks() > 0) { aoqi@0: WatcherThread::start(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Give os specific code one last chance to start aoqi@0: os::init_3(); aoqi@0: aoqi@0: create_vm_timer.end(); aoqi@0: #ifdef ASSERT aoqi@0: _vm_complete = true; aoqi@0: #endif aoqi@0: return JNI_OK; aoqi@0: } aoqi@0: aoqi@0: // type for the Agent_OnLoad and JVM_OnLoad entry points aoqi@0: extern "C" { aoqi@0: typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *); aoqi@0: } aoqi@0: // Find a command line agent library and return its entry point for aoqi@0: // -agentlib: -agentpath: -Xrun aoqi@0: // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array. aoqi@0: static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, const char *on_load_symbols[], size_t num_symbol_entries) { aoqi@0: OnLoadEntry_t on_load_entry = NULL; aoqi@0: void *library = NULL; aoqi@0: aoqi@0: if (!agent->valid()) { aoqi@0: char buffer[JVM_MAXPATHLEN]; aoqi@0: char ebuf[1024]; aoqi@0: const char *name = agent->name(); aoqi@0: const char *msg = "Could not find agent library "; aoqi@0: aoqi@0: // First check to see if agent is statically linked into executable aoqi@0: if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) { aoqi@0: library = agent->os_lib(); aoqi@0: } else if (agent->is_absolute_path()) { aoqi@0: library = os::dll_load(name, ebuf, sizeof ebuf); aoqi@0: if (library == NULL) { aoqi@0: const char *sub_msg = " in absolute path, with error: "; aoqi@0: size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; aoqi@0: char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); aoqi@0: jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); aoqi@0: // If we can't find the agent, exit. aoqi@0: vm_exit_during_initialization(buf, NULL); aoqi@0: FREE_C_HEAP_ARRAY(char, buf, mtThread); aoqi@0: } aoqi@0: } else { aoqi@0: // Try to load the agent from the standard dll directory aoqi@0: if (os::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), aoqi@0: name)) { aoqi@0: library = os::dll_load(buffer, ebuf, sizeof ebuf); aoqi@0: } aoqi@0: if (library == NULL) { // Try the local directory aoqi@0: char ns[1] = {0}; aoqi@0: if (os::dll_build_name(buffer, sizeof(buffer), ns, name)) { aoqi@0: library = os::dll_load(buffer, ebuf, sizeof ebuf); aoqi@0: } aoqi@0: if (library == NULL) { aoqi@0: const char *sub_msg = " on the library path, with error: "; aoqi@0: size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; aoqi@0: char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); aoqi@0: jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); aoqi@0: // If we can't find the agent, exit. aoqi@0: vm_exit_during_initialization(buf, NULL); aoqi@0: FREE_C_HEAP_ARRAY(char, buf, mtThread); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: agent->set_os_lib(library); aoqi@0: agent->set_valid(); aoqi@0: } aoqi@0: aoqi@0: // Find the OnLoad function. aoqi@0: on_load_entry = aoqi@0: CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent, aoqi@0: false, aoqi@0: on_load_symbols, aoqi@0: num_symbol_entries)); aoqi@0: return on_load_entry; aoqi@0: } aoqi@0: aoqi@0: // Find the JVM_OnLoad entry point aoqi@0: static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) { aoqi@0: const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS; aoqi@0: return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); aoqi@0: } aoqi@0: aoqi@0: // Find the Agent_OnLoad entry point aoqi@0: static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) { aoqi@0: const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS; aoqi@0: return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); aoqi@0: } aoqi@0: aoqi@0: // For backwards compatibility with -Xrun aoqi@0: // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be aoqi@0: // treated like -agentpath: aoqi@0: // Must be called before agent libraries are created aoqi@0: void Threads::convert_vm_init_libraries_to_agents() { aoqi@0: AgentLibrary* agent; aoqi@0: AgentLibrary* next; aoqi@0: aoqi@0: for (agent = Arguments::libraries(); agent != NULL; agent = next) { aoqi@0: next = agent->next(); // cache the next agent now as this agent may get moved off this list aoqi@0: OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); aoqi@0: aoqi@0: // If there is an JVM_OnLoad function it will get called later, aoqi@0: // otherwise see if there is an Agent_OnLoad aoqi@0: if (on_load_entry == NULL) { aoqi@0: on_load_entry = lookup_agent_on_load(agent); aoqi@0: if (on_load_entry != NULL) { aoqi@0: // switch it to the agent list -- so that Agent_OnLoad will be called, aoqi@0: // JVM_OnLoad won't be attempted and Agent_OnUnload will aoqi@0: Arguments::convert_library_to_agent(agent); aoqi@0: } else { aoqi@0: vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name()); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Create agents for -agentlib: -agentpath: and converted -Xrun aoqi@0: // Invokes Agent_OnLoad aoqi@0: // Called very early -- before JavaThreads exist aoqi@0: void Threads::create_vm_init_agents() { aoqi@0: extern struct JavaVM_ main_vm; aoqi@0: AgentLibrary* agent; aoqi@0: aoqi@0: JvmtiExport::enter_onload_phase(); aoqi@0: aoqi@0: for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) { aoqi@0: OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent); aoqi@0: aoqi@0: if (on_load_entry != NULL) { aoqi@0: // Invoke the Agent_OnLoad function aoqi@0: jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); aoqi@0: if (err != JNI_OK) { aoqi@0: vm_exit_during_initialization("agent library failed to init", agent->name()); aoqi@0: } aoqi@0: } else { aoqi@0: vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name()); aoqi@0: } aoqi@0: } aoqi@0: JvmtiExport::enter_primordial_phase(); aoqi@0: } aoqi@0: aoqi@0: extern "C" { aoqi@0: typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *); aoqi@0: } aoqi@0: aoqi@0: void Threads::shutdown_vm_agents() { aoqi@0: // Send any Agent_OnUnload notifications aoqi@0: const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS; aoqi@0: size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols); aoqi@0: extern struct JavaVM_ main_vm; aoqi@0: for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) { aoqi@0: aoqi@0: // Find the Agent_OnUnload function. aoqi@0: Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t, aoqi@0: os::find_agent_function(agent, aoqi@0: false, aoqi@0: on_unload_symbols, aoqi@0: num_symbol_entries)); aoqi@0: aoqi@0: // Invoke the Agent_OnUnload function aoqi@0: if (unload_entry != NULL) { aoqi@0: JavaThread* thread = JavaThread::current(); aoqi@0: ThreadToNativeFromVM ttn(thread); aoqi@0: HandleMark hm(thread); aoqi@0: (*unload_entry)(&main_vm); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries aoqi@0: // Invokes JVM_OnLoad aoqi@0: void Threads::create_vm_init_libraries() { aoqi@0: extern struct JavaVM_ main_vm; aoqi@0: AgentLibrary* agent; aoqi@0: aoqi@0: for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) { aoqi@0: OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); aoqi@0: aoqi@0: if (on_load_entry != NULL) { aoqi@0: // Invoke the JVM_OnLoad function aoqi@0: JavaThread* thread = JavaThread::current(); aoqi@0: ThreadToNativeFromVM ttn(thread); aoqi@0: HandleMark hm(thread); aoqi@0: jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); aoqi@0: if (err != JNI_OK) { aoqi@0: vm_exit_during_initialization("-Xrun library failed to init", agent->name()); aoqi@0: } aoqi@0: } else { aoqi@0: vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name()); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Last thread running calls java.lang.Shutdown.shutdown() aoqi@0: void JavaThread::invoke_shutdown_hooks() { aoqi@0: HandleMark hm(this); aoqi@0: aoqi@0: // We could get here with a pending exception, if so clear it now. aoqi@0: if (this->has_pending_exception()) { aoqi@0: this->clear_pending_exception(); aoqi@0: } aoqi@0: aoqi@0: EXCEPTION_MARK; aoqi@0: Klass* k = aoqi@0: SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(), aoqi@0: THREAD); aoqi@0: if (k != NULL) { aoqi@0: // SystemDictionary::resolve_or_null will return null if there was aoqi@0: // an exception. If we cannot load the Shutdown class, just don't aoqi@0: // call Shutdown.shutdown() at all. This will mean the shutdown hooks aoqi@0: // and finalizers (if runFinalizersOnExit is set) won't be run. aoqi@0: // Note that if a shutdown hook was registered or runFinalizersOnExit aoqi@0: // was called, the Shutdown class would have already been loaded aoqi@0: // (Runtime.addShutdownHook and runFinalizersOnExit will load it). aoqi@0: instanceKlassHandle shutdown_klass (THREAD, k); aoqi@0: JavaValue result(T_VOID); aoqi@0: JavaCalls::call_static(&result, aoqi@0: shutdown_klass, aoqi@0: vmSymbols::shutdown_method_name(), aoqi@0: vmSymbols::void_method_signature(), aoqi@0: THREAD); aoqi@0: } aoqi@0: CLEAR_PENDING_EXCEPTION; aoqi@0: } aoqi@0: aoqi@0: // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when aoqi@0: // the program falls off the end of main(). Another VM exit path is through aoqi@0: // vm_exit() when the program calls System.exit() to return a value or when aoqi@0: // there is a serious error in VM. The two shutdown paths are not exactly aoqi@0: // the same, but they share Shutdown.shutdown() at Java level and before_exit() aoqi@0: // and VM_Exit op at VM level. aoqi@0: // aoqi@0: // Shutdown sequence: aoqi@0: // + Shutdown native memory tracking if it is on aoqi@0: // + Wait until we are the last non-daemon thread to execute aoqi@0: // <-- every thing is still working at this moment --> aoqi@0: // + Call java.lang.Shutdown.shutdown(), which will invoke Java level aoqi@0: // shutdown hooks, run finalizers if finalization-on-exit aoqi@0: // + Call before_exit(), prepare for VM exit aoqi@0: // > run VM level shutdown hooks (they are registered through JVM_OnExit(), aoqi@0: // currently the only user of this mechanism is File.deleteOnExit()) aoqi@0: // > stop flat profiler, StatSampler, watcher thread, CMS threads, aoqi@0: // post thread end and vm death events to JVMTI, aoqi@0: // stop signal thread aoqi@0: // + Call JavaThread::exit(), it will: aoqi@0: // > release JNI handle blocks, remove stack guard pages aoqi@0: // > remove this thread from Threads list aoqi@0: // <-- no more Java code from this thread after this point --> aoqi@0: // + Stop VM thread, it will bring the remaining VM to a safepoint and stop aoqi@0: // the compiler threads at safepoint aoqi@0: // <-- do not use anything that could get blocked by Safepoint --> aoqi@0: // + Disable tracing at JNI/JVM barriers aoqi@0: // + Set _vm_exited flag for threads that are still running native code aoqi@0: // + Delete this thread aoqi@0: // + Call exit_globals() aoqi@0: // > deletes tty aoqi@0: // > deletes PerfMemory resources aoqi@0: // + Return to caller aoqi@0: aoqi@0: bool Threads::destroy_vm() { aoqi@0: JavaThread* thread = JavaThread::current(); aoqi@0: aoqi@0: #ifdef ASSERT aoqi@0: _vm_complete = false; aoqi@0: #endif aoqi@0: // Wait until we are the last non-daemon thread to execute aoqi@0: { MutexLocker nu(Threads_lock); aoqi@0: while (Threads::number_of_non_daemon_threads() > 1 ) aoqi@0: // This wait should make safepoint checks, wait without a timeout, aoqi@0: // and wait as a suspend-equivalent condition. aoqi@0: // aoqi@0: // Note: If the FlatProfiler is running and this thread is waiting aoqi@0: // for another non-daemon thread to finish, then the FlatProfiler aoqi@0: // is waiting for the external suspend request on this thread to aoqi@0: // complete. wait_for_ext_suspend_completion() will eventually aoqi@0: // timeout, but that takes time. Making this wait a suspend- aoqi@0: // equivalent condition solves that timeout problem. aoqi@0: // aoqi@0: Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0, aoqi@0: Mutex::_as_suspend_equivalent_flag); aoqi@0: } aoqi@0: aoqi@0: // Hang forever on exit if we are reporting an error. aoqi@0: if (ShowMessageBoxOnError && is_error_reported()) { aoqi@0: os::infinite_sleep(); aoqi@0: } aoqi@0: os::wait_for_keypress_at_exit(); aoqi@0: aoqi@0: if (JDK_Version::is_jdk12x_version()) { aoqi@0: // We are the last thread running, so check if finalizers should be run. aoqi@0: // For 1.3 or later this is done in thread->invoke_shutdown_hooks() aoqi@0: HandleMark rm(thread); aoqi@0: Universe::run_finalizers_on_exit(); aoqi@0: } else { aoqi@0: // run Java level shutdown hooks aoqi@0: thread->invoke_shutdown_hooks(); aoqi@0: } aoqi@0: aoqi@0: before_exit(thread); aoqi@0: aoqi@0: thread->exit(true); aoqi@0: aoqi@0: // Stop VM thread. aoqi@0: { aoqi@0: // 4945125 The vm thread comes to a safepoint during exit. aoqi@0: // GC vm_operations can get caught at the safepoint, and the aoqi@0: // heap is unparseable if they are caught. Grab the Heap_lock aoqi@0: // to prevent this. The GC vm_operations will not be able to aoqi@0: // queue until after the vm thread is dead. After this point, aoqi@0: // we'll never emerge out of the safepoint before the VM exits. aoqi@0: aoqi@0: MutexLocker ml(Heap_lock); aoqi@0: aoqi@0: VMThread::wait_for_vm_thread_exit(); aoqi@0: assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint"); aoqi@0: VMThread::destroy(); aoqi@0: } aoqi@0: aoqi@0: // clean up ideal graph printers aoqi@0: #if defined(COMPILER2) && !defined(PRODUCT) aoqi@0: IdealGraphPrinter::clean_up(); aoqi@0: #endif aoqi@0: aoqi@0: // Now, all Java threads are gone except daemon threads. Daemon threads aoqi@0: // running Java code or in VM are stopped by the Safepoint. However, aoqi@0: // daemon threads executing native code are still running. But they aoqi@0: // will be stopped at native=>Java/VM barriers. Note that we can't aoqi@0: // simply kill or suspend them, as it is inherently deadlock-prone. aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: // disable function tracing at JNI/JVM barriers aoqi@0: TraceJNICalls = false; aoqi@0: TraceJVMCalls = false; aoqi@0: TraceRuntimeCalls = false; aoqi@0: #endif aoqi@0: aoqi@0: VM_Exit::set_vm_exited(); aoqi@0: aoqi@0: notify_vm_shutdown(); aoqi@0: aoqi@0: delete thread; aoqi@0: aoqi@0: // exit_globals() will delete tty aoqi@0: exit_globals(); aoqi@0: aoqi@0: return true; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: jboolean Threads::is_supported_jni_version_including_1_1(jint version) { aoqi@0: if (version == JNI_VERSION_1_1) return JNI_TRUE; aoqi@0: return is_supported_jni_version(version); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: jboolean Threads::is_supported_jni_version(jint version) { aoqi@0: if (version == JNI_VERSION_1_2) return JNI_TRUE; aoqi@0: if (version == JNI_VERSION_1_4) return JNI_TRUE; aoqi@0: if (version == JNI_VERSION_1_6) return JNI_TRUE; aoqi@0: if (version == JNI_VERSION_1_8) return JNI_TRUE; aoqi@0: return JNI_FALSE; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void Threads::add(JavaThread* p, bool force_daemon) { aoqi@0: // The threads lock must be owned at this point aoqi@0: assert_locked_or_safepoint(Threads_lock); aoqi@0: aoqi@0: // See the comment for this method in thread.hpp for its purpose and aoqi@0: // why it is called here. aoqi@0: p->initialize_queues(); aoqi@0: p->set_next(_thread_list); aoqi@0: _thread_list = p; aoqi@0: _number_of_threads++; aoqi@0: oop threadObj = p->threadObj(); aoqi@0: bool daemon = true; aoqi@0: // Bootstrapping problem: threadObj can be null for initial aoqi@0: // JavaThread (or for threads attached via JNI) aoqi@0: if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) { aoqi@0: _number_of_non_daemon_threads++; aoqi@0: daemon = false; aoqi@0: } aoqi@0: aoqi@0: p->set_safepoint_visible(true); aoqi@0: aoqi@0: ThreadService::add_thread(p, daemon); aoqi@0: aoqi@0: // Possible GC point. aoqi@0: Events::log(p, "Thread added: " INTPTR_FORMAT, p); aoqi@0: } aoqi@0: aoqi@0: void Threads::remove(JavaThread* p) { aoqi@0: // Extra scope needed for Thread_lock, so we can check aoqi@0: // that we do not remove thread without safepoint code notice aoqi@0: { MutexLocker ml(Threads_lock); aoqi@0: aoqi@0: assert(includes(p), "p must be present"); aoqi@0: aoqi@0: JavaThread* current = _thread_list; aoqi@0: JavaThread* prev = NULL; aoqi@0: aoqi@0: while (current != p) { aoqi@0: prev = current; aoqi@0: current = current->next(); aoqi@0: } aoqi@0: aoqi@0: if (prev) { aoqi@0: prev->set_next(current->next()); aoqi@0: } else { aoqi@0: _thread_list = p->next(); aoqi@0: } aoqi@0: _number_of_threads--; aoqi@0: oop threadObj = p->threadObj(); aoqi@0: bool daemon = true; aoqi@0: if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) { aoqi@0: _number_of_non_daemon_threads--; aoqi@0: daemon = false; aoqi@0: aoqi@0: // Only one thread left, do a notify on the Threads_lock so a thread waiting aoqi@0: // on destroy_vm will wake up. aoqi@0: if (number_of_non_daemon_threads() == 1) aoqi@0: Threads_lock->notify_all(); aoqi@0: } aoqi@0: ThreadService::remove_thread(p, daemon); aoqi@0: aoqi@0: // Make sure that safepoint code disregard this thread. This is needed since aoqi@0: // the thread might mess around with locks after this point. This can cause it aoqi@0: // to do callbacks into the safepoint code. However, the safepoint code is not aware aoqi@0: // of this thread since it is removed from the queue. aoqi@0: p->set_terminated_value(); aoqi@0: aoqi@0: // Now, this thread is not visible to safepoint aoqi@0: p->set_safepoint_visible(false); aoqi@0: // once the thread becomes safepoint invisible, we can not use its per-thread aoqi@0: // recorder. And Threads::do_threads() no longer walks this thread, so we have aoqi@0: // to release its per-thread recorder here. aoqi@0: MemTracker::thread_exiting(p); aoqi@0: } // unlock Threads_lock aoqi@0: aoqi@0: // Since Events::log uses a lock, we grab it outside the Threads_lock aoqi@0: Events::log(p, "Thread exited: " INTPTR_FORMAT, p); aoqi@0: } aoqi@0: aoqi@0: // Threads_lock must be held when this is called (or must be called during a safepoint) aoqi@0: bool Threads::includes(JavaThread* p) { aoqi@0: assert(Threads_lock->is_locked(), "sanity check"); aoqi@0: ALL_JAVA_THREADS(q) { aoqi@0: if (q == p ) { aoqi@0: return true; aoqi@0: } aoqi@0: } aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: // Operations on the Threads list for GC. These are not explicitly locked, aoqi@0: // but the garbage collector must provide a safe context for them to run. aoqi@0: // In particular, these things should never be called when the Threads_lock aoqi@0: // is held by some other thread. (Note: the Safepoint abstraction also aoqi@0: // uses the Threads_lock to gurantee this property. It also makes sure that aoqi@0: // all threads gets blocked when exiting or starting). aoqi@0: aoqi@0: void Threads::oops_do(OopClosure* f, CLDToOopClosure* cld_f, CodeBlobClosure* cf) { aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: p->oops_do(f, cld_f, cf); aoqi@0: } aoqi@0: VMThread::vm_thread()->oops_do(f, cld_f, cf); aoqi@0: } aoqi@0: aoqi@0: void Threads::possibly_parallel_oops_do(OopClosure* f, CLDToOopClosure* cld_f, CodeBlobClosure* cf) { aoqi@0: // Introduce a mechanism allowing parallel threads to claim threads as aoqi@0: // root groups. Overhead should be small enough to use all the time, aoqi@0: // even in sequential code. aoqi@0: SharedHeap* sh = SharedHeap::heap(); aoqi@0: // Cannot yet substitute active_workers for n_par_threads aoqi@0: // because of G1CollectedHeap::verify() use of aoqi@0: // SharedHeap::process_strong_roots(). n_par_threads == 0 will aoqi@0: // turn off parallelism in process_strong_roots while active_workers aoqi@0: // is being used for parallelism elsewhere. aoqi@0: bool is_par = sh->n_par_threads() > 0; aoqi@0: assert(!is_par || aoqi@0: (SharedHeap::heap()->n_par_threads() == aoqi@0: SharedHeap::heap()->workers()->active_workers()), "Mismatch"); aoqi@0: int cp = SharedHeap::heap()->strong_roots_parity(); aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: if (p->claim_oops_do(is_par, cp)) { aoqi@0: p->oops_do(f, cld_f, cf); aoqi@0: } aoqi@0: } aoqi@0: VMThread* vmt = VMThread::vm_thread(); aoqi@0: if (vmt->claim_oops_do(is_par, cp)) { aoqi@0: vmt->oops_do(f, cld_f, cf); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: // Used by ParallelScavenge aoqi@0: void Threads::create_thread_roots_tasks(GCTaskQueue* q) { aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: q->enqueue(new ThreadRootsTask(p)); aoqi@0: } aoqi@0: q->enqueue(new ThreadRootsTask(VMThread::vm_thread())); aoqi@0: } aoqi@0: aoqi@0: // Used by Parallel Old aoqi@0: void Threads::create_thread_roots_marking_tasks(GCTaskQueue* q) { aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: q->enqueue(new ThreadRootsMarkingTask(p)); aoqi@0: } aoqi@0: q->enqueue(new ThreadRootsMarkingTask(VMThread::vm_thread())); aoqi@0: } aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: aoqi@0: void Threads::nmethods_do(CodeBlobClosure* cf) { aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: p->nmethods_do(cf); aoqi@0: } aoqi@0: VMThread::vm_thread()->nmethods_do(cf); aoqi@0: } aoqi@0: aoqi@0: void Threads::metadata_do(void f(Metadata*)) { aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: p->metadata_do(f); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void Threads::gc_epilogue() { aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: p->gc_epilogue(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void Threads::gc_prologue() { aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: p->gc_prologue(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void Threads::deoptimized_wrt_marked_nmethods() { aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: p->deoptimized_wrt_marked_nmethods(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // Get count Java threads that are waiting to enter the specified monitor. aoqi@0: GrowableArray* Threads::get_pending_threads(int count, aoqi@0: address monitor, bool doLock) { aoqi@0: assert(doLock || SafepointSynchronize::is_at_safepoint(), aoqi@0: "must grab Threads_lock or be at safepoint"); aoqi@0: GrowableArray* result = new GrowableArray(count); aoqi@0: aoqi@0: int i = 0; aoqi@0: { aoqi@0: MutexLockerEx ml(doLock ? Threads_lock : NULL); aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: if (p->is_Compiler_thread()) continue; aoqi@0: aoqi@0: address pending = (address)p->current_pending_monitor(); aoqi@0: if (pending == monitor) { // found a match aoqi@0: if (i < count) result->append(p); // save the first count matches aoqi@0: i++; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: return result; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: JavaThread *Threads::owning_thread_from_monitor_owner(address owner, bool doLock) { aoqi@0: assert(doLock || aoqi@0: Threads_lock->owned_by_self() || aoqi@0: SafepointSynchronize::is_at_safepoint(), aoqi@0: "must grab Threads_lock or be at safepoint"); aoqi@0: aoqi@0: // NULL owner means not locked so we can skip the search aoqi@0: if (owner == NULL) return NULL; aoqi@0: aoqi@0: { aoqi@0: MutexLockerEx ml(doLock ? Threads_lock : NULL); aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: // first, see if owner is the address of a Java thread aoqi@0: if (owner == (address)p) return p; aoqi@0: } aoqi@0: } aoqi@0: // Cannot assert on lack of success here since this function may be aoqi@0: // used by code that is trying to report useful problem information aoqi@0: // like deadlock detection. aoqi@0: if (UseHeavyMonitors) return NULL; aoqi@0: aoqi@0: // aoqi@0: // If we didn't find a matching Java thread and we didn't force use of aoqi@0: // heavyweight monitors, then the owner is the stack address of the aoqi@0: // Lock Word in the owning Java thread's stack. aoqi@0: // aoqi@0: JavaThread* the_owner = NULL; aoqi@0: { aoqi@0: MutexLockerEx ml(doLock ? Threads_lock : NULL); aoqi@0: ALL_JAVA_THREADS(q) { aoqi@0: if (q->is_lock_owned(owner)) { aoqi@0: the_owner = q; aoqi@0: break; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: // cannot assert on lack of success here; see above comment aoqi@0: return the_owner; aoqi@0: } aoqi@0: aoqi@0: // Threads::print_on() is called at safepoint by VM_PrintThreads operation. aoqi@0: void Threads::print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks) { aoqi@0: char buf[32]; aoqi@0: st->print_cr("%s", os::local_time_string(buf, sizeof(buf))); aoqi@0: aoqi@0: st->print_cr("Full thread dump %s (%s %s):", aoqi@0: Abstract_VM_Version::vm_name(), aoqi@0: Abstract_VM_Version::vm_release(), aoqi@0: Abstract_VM_Version::vm_info_string() aoqi@0: ); aoqi@0: st->cr(); aoqi@0: aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: // Dump concurrent locks aoqi@0: ConcurrentLocksDump concurrent_locks; aoqi@0: if (print_concurrent_locks) { aoqi@0: concurrent_locks.dump_at_safepoint(); aoqi@0: } aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: ResourceMark rm; aoqi@0: p->print_on(st); aoqi@0: if (print_stacks) { aoqi@0: if (internal_format) { aoqi@0: p->trace_stack(); aoqi@0: } else { aoqi@0: p->print_stack_on(st); aoqi@0: } aoqi@0: } aoqi@0: st->cr(); aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: if (print_concurrent_locks) { aoqi@0: concurrent_locks.print_locks_on(p, st); aoqi@0: } aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: } aoqi@0: aoqi@0: VMThread::vm_thread()->print_on(st); aoqi@0: st->cr(); aoqi@0: Universe::heap()->print_gc_threads_on(st); aoqi@0: WatcherThread* wt = WatcherThread::watcher_thread(); aoqi@0: if (wt != NULL) { aoqi@0: wt->print_on(st); aoqi@0: st->cr(); aoqi@0: } aoqi@0: CompileBroker::print_compiler_threads_on(st); aoqi@0: st->flush(); aoqi@0: } aoqi@0: aoqi@0: // Threads::print_on_error() is called by fatal error handler. It's possible aoqi@0: // that VM is not at safepoint and/or current thread is inside signal handler. aoqi@0: // Don't print stack trace, as the stack may not be walkable. Don't allocate aoqi@0: // memory (even in resource area), it might deadlock the error handler. aoqi@0: void Threads::print_on_error(outputStream* st, Thread* current, char* buf, int buflen) { aoqi@0: bool found_current = false; aoqi@0: st->print_cr("Java Threads: ( => current thread )"); aoqi@0: ALL_JAVA_THREADS(thread) { aoqi@0: bool is_current = (current == thread); aoqi@0: found_current = found_current || is_current; aoqi@0: aoqi@0: st->print("%s", is_current ? "=>" : " "); aoqi@0: aoqi@0: st->print(PTR_FORMAT, thread); aoqi@0: st->print(" "); aoqi@0: thread->print_on_error(st, buf, buflen); aoqi@0: st->cr(); aoqi@0: } aoqi@0: st->cr(); aoqi@0: aoqi@0: st->print_cr("Other Threads:"); aoqi@0: if (VMThread::vm_thread()) { aoqi@0: bool is_current = (current == VMThread::vm_thread()); aoqi@0: found_current = found_current || is_current; aoqi@0: st->print("%s", current == VMThread::vm_thread() ? "=>" : " "); aoqi@0: aoqi@0: st->print(PTR_FORMAT, VMThread::vm_thread()); aoqi@0: st->print(" "); aoqi@0: VMThread::vm_thread()->print_on_error(st, buf, buflen); aoqi@0: st->cr(); aoqi@0: } aoqi@0: WatcherThread* wt = WatcherThread::watcher_thread(); aoqi@0: if (wt != NULL) { aoqi@0: bool is_current = (current == wt); aoqi@0: found_current = found_current || is_current; aoqi@0: st->print("%s", is_current ? "=>" : " "); aoqi@0: aoqi@0: st->print(PTR_FORMAT, wt); aoqi@0: st->print(" "); aoqi@0: wt->print_on_error(st, buf, buflen); aoqi@0: st->cr(); aoqi@0: } aoqi@0: if (!found_current) { aoqi@0: st->cr(); aoqi@0: st->print("=>" PTR_FORMAT " (exited) ", current); aoqi@0: current->print_on_error(st, buf, buflen); aoqi@0: st->cr(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Internal SpinLock and Mutex aoqi@0: // Based on ParkEvent aoqi@0: aoqi@0: // Ad-hoc mutual exclusion primitives: SpinLock and Mux aoqi@0: // aoqi@0: // We employ SpinLocks _only for low-contention, fixed-length aoqi@0: // short-duration critical sections where we're concerned aoqi@0: // about native mutex_t or HotSpot Mutex:: latency. aoqi@0: // The mux construct provides a spin-then-block mutual exclusion aoqi@0: // mechanism. aoqi@0: // aoqi@0: // Testing has shown that contention on the ListLock guarding gFreeList aoqi@0: // is common. If we implement ListLock as a simple SpinLock it's common aoqi@0: // for the JVM to devolve to yielding with little progress. This is true aoqi@0: // despite the fact that the critical sections protected by ListLock are aoqi@0: // extremely short. aoqi@0: // aoqi@0: // TODO-FIXME: ListLock should be of type SpinLock. aoqi@0: // We should make this a 1st-class type, integrated into the lock aoqi@0: // hierarchy as leaf-locks. Critically, the SpinLock structure aoqi@0: // should have sufficient padding to avoid false-sharing and excessive aoqi@0: // cache-coherency traffic. aoqi@0: aoqi@0: aoqi@0: typedef volatile int SpinLockT ; aoqi@0: aoqi@0: void Thread::SpinAcquire (volatile int * adr, const char * LockName) { aoqi@0: if (Atomic::cmpxchg (1, adr, 0) == 0) { aoqi@0: return ; // normal fast-path return aoqi@0: } aoqi@0: aoqi@0: // Slow-path : We've encountered contention -- Spin/Yield/Block strategy. aoqi@0: TEVENT (SpinAcquire - ctx) ; aoqi@0: int ctr = 0 ; aoqi@0: int Yields = 0 ; aoqi@0: for (;;) { aoqi@0: while (*adr != 0) { aoqi@0: ++ctr ; aoqi@0: if ((ctr & 0xFFF) == 0 || !os::is_MP()) { aoqi@0: if (Yields > 5) { aoqi@0: os::naked_short_sleep(1); aoqi@0: } else { aoqi@0: os::NakedYield() ; aoqi@0: ++Yields ; aoqi@0: } aoqi@0: } else { aoqi@0: SpinPause() ; aoqi@0: } aoqi@0: } aoqi@0: if (Atomic::cmpxchg (1, adr, 0) == 0) return ; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void Thread::SpinRelease (volatile int * adr) { aoqi@0: assert (*adr != 0, "invariant") ; aoqi@0: OrderAccess::fence() ; // guarantee at least release consistency. aoqi@0: // Roach-motel semantics. aoqi@0: // It's safe if subsequent LDs and STs float "up" into the critical section, aoqi@0: // but prior LDs and STs within the critical section can't be allowed aoqi@0: // to reorder or float past the ST that releases the lock. aoqi@0: *adr = 0 ; aoqi@0: } aoqi@0: aoqi@0: // muxAcquire and muxRelease: aoqi@0: // aoqi@0: // * muxAcquire and muxRelease support a single-word lock-word construct. aoqi@0: // The LSB of the word is set IFF the lock is held. aoqi@0: // The remainder of the word points to the head of a singly-linked list aoqi@0: // of threads blocked on the lock. aoqi@0: // aoqi@0: // * The current implementation of muxAcquire-muxRelease uses its own aoqi@0: // dedicated Thread._MuxEvent instance. If we're interested in aoqi@0: // minimizing the peak number of extant ParkEvent instances then aoqi@0: // we could eliminate _MuxEvent and "borrow" _ParkEvent as long aoqi@0: // as certain invariants were satisfied. Specifically, care would need aoqi@0: // to be taken with regards to consuming unpark() "permits". aoqi@0: // A safe rule of thumb is that a thread would never call muxAcquire() aoqi@0: // if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently aoqi@0: // park(). Otherwise the _ParkEvent park() operation in muxAcquire() could aoqi@0: // consume an unpark() permit intended for monitorenter, for instance. aoqi@0: // One way around this would be to widen the restricted-range semaphore aoqi@0: // implemented in park(). Another alternative would be to provide aoqi@0: // multiple instances of the PlatformEvent() for each thread. One aoqi@0: // instance would be dedicated to muxAcquire-muxRelease, for instance. aoqi@0: // aoqi@0: // * Usage: aoqi@0: // -- Only as leaf locks aoqi@0: // -- for short-term locking only as muxAcquire does not perform aoqi@0: // thread state transitions. aoqi@0: // aoqi@0: // Alternatives: aoqi@0: // * We could implement muxAcquire and muxRelease with MCS or CLH locks aoqi@0: // but with parking or spin-then-park instead of pure spinning. aoqi@0: // * Use Taura-Oyama-Yonenzawa locks. aoqi@0: // * It's possible to construct a 1-0 lock if we encode the lockword as aoqi@0: // (List,LockByte). Acquire will CAS the full lockword while Release aoqi@0: // will STB 0 into the LockByte. The 1-0 scheme admits stranding, so aoqi@0: // acquiring threads use timers (ParkTimed) to detect and recover from aoqi@0: // the stranding window. Thread/Node structures must be aligned on 256-byte aoqi@0: // boundaries by using placement-new. aoqi@0: // * Augment MCS with advisory back-link fields maintained with CAS(). aoqi@0: // Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner. aoqi@0: // The validity of the backlinks must be ratified before we trust the value. aoqi@0: // If the backlinks are invalid the exiting thread must back-track through the aoqi@0: // the forward links, which are always trustworthy. aoqi@0: // * Add a successor indication. The LockWord is currently encoded as aoqi@0: // (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable aoqi@0: // to provide the usual futile-wakeup optimization. aoqi@0: // See RTStt for details. aoqi@0: // * Consider schedctl.sc_nopreempt to cover the critical section. aoqi@0: // aoqi@0: aoqi@0: aoqi@0: typedef volatile intptr_t MutexT ; // Mux Lock-word aoqi@0: enum MuxBits { LOCKBIT = 1 } ; aoqi@0: aoqi@0: void Thread::muxAcquire (volatile intptr_t * Lock, const char * LockName) { aoqi@0: intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ; aoqi@0: if (w == 0) return ; aoqi@0: if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { aoqi@0: return ; aoqi@0: } aoqi@0: aoqi@0: TEVENT (muxAcquire - Contention) ; aoqi@0: ParkEvent * const Self = Thread::current()->_MuxEvent ; aoqi@0: assert ((intptr_t(Self) & LOCKBIT) == 0, "invariant") ; aoqi@0: for (;;) { aoqi@0: int its = (os::is_MP() ? 100 : 0) + 1 ; aoqi@0: aoqi@0: // Optional spin phase: spin-then-park strategy aoqi@0: while (--its >= 0) { aoqi@0: w = *Lock ; aoqi@0: if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { aoqi@0: return ; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: Self->reset() ; aoqi@0: Self->OnList = intptr_t(Lock) ; aoqi@0: // The following fence() isn't _strictly necessary as the subsequent aoqi@0: // CAS() both serializes execution and ratifies the fetched *Lock value. aoqi@0: OrderAccess::fence(); aoqi@0: for (;;) { aoqi@0: w = *Lock ; aoqi@0: if ((w & LOCKBIT) == 0) { aoqi@0: if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { aoqi@0: Self->OnList = 0 ; // hygiene - allows stronger asserts aoqi@0: return ; aoqi@0: } aoqi@0: continue ; // Interference -- *Lock changed -- Just retry aoqi@0: } aoqi@0: assert (w & LOCKBIT, "invariant") ; aoqi@0: Self->ListNext = (ParkEvent *) (w & ~LOCKBIT ); aoqi@0: if (Atomic::cmpxchg_ptr (intptr_t(Self)|LOCKBIT, Lock, w) == w) break ; aoqi@0: } aoqi@0: aoqi@0: while (Self->OnList != 0) { aoqi@0: Self->park() ; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) { aoqi@0: intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ; aoqi@0: if (w == 0) return ; aoqi@0: if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { aoqi@0: return ; aoqi@0: } aoqi@0: aoqi@0: TEVENT (muxAcquire - Contention) ; aoqi@0: ParkEvent * ReleaseAfter = NULL ; aoqi@0: if (ev == NULL) { aoqi@0: ev = ReleaseAfter = ParkEvent::Allocate (NULL) ; aoqi@0: } aoqi@0: assert ((intptr_t(ev) & LOCKBIT) == 0, "invariant") ; aoqi@0: for (;;) { aoqi@0: guarantee (ev->OnList == 0, "invariant") ; aoqi@0: int its = (os::is_MP() ? 100 : 0) + 1 ; aoqi@0: aoqi@0: // Optional spin phase: spin-then-park strategy aoqi@0: while (--its >= 0) { aoqi@0: w = *Lock ; aoqi@0: if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { aoqi@0: if (ReleaseAfter != NULL) { aoqi@0: ParkEvent::Release (ReleaseAfter) ; aoqi@0: } aoqi@0: return ; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: ev->reset() ; aoqi@0: ev->OnList = intptr_t(Lock) ; aoqi@0: // The following fence() isn't _strictly necessary as the subsequent aoqi@0: // CAS() both serializes execution and ratifies the fetched *Lock value. aoqi@0: OrderAccess::fence(); aoqi@0: for (;;) { aoqi@0: w = *Lock ; aoqi@0: if ((w & LOCKBIT) == 0) { aoqi@0: if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { aoqi@0: ev->OnList = 0 ; aoqi@0: // We call ::Release while holding the outer lock, thus aoqi@0: // artificially lengthening the critical section. aoqi@0: // Consider deferring the ::Release() until the subsequent unlock(), aoqi@0: // after we've dropped the outer lock. aoqi@0: if (ReleaseAfter != NULL) { aoqi@0: ParkEvent::Release (ReleaseAfter) ; aoqi@0: } aoqi@0: return ; aoqi@0: } aoqi@0: continue ; // Interference -- *Lock changed -- Just retry aoqi@0: } aoqi@0: assert (w & LOCKBIT, "invariant") ; aoqi@0: ev->ListNext = (ParkEvent *) (w & ~LOCKBIT ); aoqi@0: if (Atomic::cmpxchg_ptr (intptr_t(ev)|LOCKBIT, Lock, w) == w) break ; aoqi@0: } aoqi@0: aoqi@0: while (ev->OnList != 0) { aoqi@0: ev->park() ; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Release() must extract a successor from the list and then wake that thread. aoqi@0: // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme aoqi@0: // similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based aoqi@0: // Release() would : aoqi@0: // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list. aoqi@0: // (B) Extract a successor from the private list "in-hand" aoqi@0: // (C) attempt to CAS() the residual back into *Lock over null. aoqi@0: // If there were any newly arrived threads and the CAS() would fail. aoqi@0: // In that case Release() would detach the RATs, re-merge the list in-hand aoqi@0: // with the RATs and repeat as needed. Alternately, Release() might aoqi@0: // detach and extract a successor, but then pass the residual list to the wakee. aoqi@0: // The wakee would be responsible for reattaching and remerging before it aoqi@0: // competed for the lock. aoqi@0: // aoqi@0: // Both "pop" and DMR are immune from ABA corruption -- there can be aoqi@0: // multiple concurrent pushers, but only one popper or detacher. aoqi@0: // This implementation pops from the head of the list. This is unfair, aoqi@0: // but tends to provide excellent throughput as hot threads remain hot. aoqi@0: // (We wake recently run threads first). aoqi@0: aoqi@0: void Thread::muxRelease (volatile intptr_t * Lock) { aoqi@0: for (;;) { aoqi@0: const intptr_t w = Atomic::cmpxchg_ptr (0, Lock, LOCKBIT) ; aoqi@0: assert (w & LOCKBIT, "invariant") ; aoqi@0: if (w == LOCKBIT) return ; aoqi@0: ParkEvent * List = (ParkEvent *) (w & ~LOCKBIT) ; aoqi@0: assert (List != NULL, "invariant") ; aoqi@0: assert (List->OnList == intptr_t(Lock), "invariant") ; aoqi@0: ParkEvent * nxt = List->ListNext ; aoqi@0: aoqi@0: // The following CAS() releases the lock and pops the head element. aoqi@0: if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) { aoqi@0: continue ; aoqi@0: } aoqi@0: List->OnList = 0 ; aoqi@0: OrderAccess::fence() ; aoqi@0: List->unpark () ; aoqi@0: return ; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void Threads::verify() { aoqi@0: ALL_JAVA_THREADS(p) { aoqi@0: p->verify(); aoqi@0: } aoqi@0: VMThread* thread = VMThread::vm_thread(); aoqi@0: if (thread != NULL) thread->verify(); aoqi@0: }