thread.cpp revision 1115
2362N/A * Copyright 1997-2009 Sun Microsystems, Inc. All Rights Reserved. 0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 0N/A * This code is free software; you can redistribute it and/or modify it 0N/A * under the terms of the GNU General Public License version 2 only, as 0N/A * published by the Free Software Foundation. 0N/A * This code is distributed in the hope that it will be useful, but WITHOUT 0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 0N/A * version 2 for more details (a copy is included in the LICENSE file that 0N/A * accompanied this code). 0N/A * You should have received a copy of the GNU General Public License version 0N/A * 2 along with this work; if not, write to the Free Software Foundation, 0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 2362N/A * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 2362N/A * CA 95054 USA or visit www.sun.com if you need additional information or 0N/A#
include "incls/_precompiled.incl" 0N/A// Only bother with this argument setup if dtrace is available 0N/A#
else // ndef DTRACE_ENABLED 0N/A#
endif // ndef DTRACE_ENABLED // - ConcurrentMarkSweepThread // ======= Thread ======== // Support for forcing alignment of thread objects for biased locking "JavaThread alignment code overflowed allocated storage");
void Thread::
operator delete(
void* p) {
// Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread, // allocated data structures // This initial value ==> never claimed. // the handle mark links itself to last_handle_mark // thread-specific hashCode stream generator state - Marsaglia shift-xor form _hashStateZ =
0x8767 ;
// (int)(3579807591LL & 0xffff) ; // Many of the following fields are effectively final - immutable // Note that nascent threads can't use the Native Monitor-Mutex // construct until the _MutexEvent is initialized ... // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents // we might instead use a stack of ParkEvents that we could provision on-demand. // The stack would act as a cache to avoid calls to ParkEvent::Allocate() #
endif // CHECK_UNHANDLED_OOPS "bug in forced alignment of thread objects");
// Note: Make sure this method only calls // non-blocking operations. Otherwise, it might not work // During Java thread startup, safepoint code should allow this // method to complete because it may need to allocate memory to // store information for the new thread. // initialize structure dependent on thread local storage // set up any platform-specific state. // Reclaim the objectmonitors from the omFreeList of the moribund thread. // deallocate data structures // since the handle marks are using the handle area, we have to deallocated the root // handle mark before deallocating the thread's handle area, // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads. // We NULL out the fields for good hygiene. // osthread() can be NULL, if creation of thread failed. // clear thread local storage if the Thread is deleting itself // In the case where we're not the current thread, invalidate all the // caches in case some code tries to get the current thread or the // thread that was destroyed, and gets stale information. // NOTE: dummy function for assertion purpose. // Private method to check for dangling thread pointer "possibility of dangling Thread pointer");
// Tracing method for basic thread operations const char *
name =
"non-Java thread";
// The Threads_lock must be held to get information about // this thread but may not be in some situations when // tracing thread events. // Start is different from resume in that its safety is guaranteed by context or // being called from a Java method synchronized on the Thread object. // Initialize the thread state to RUNNABLE before starting this thread. // Can not set it after the thread started because we do not know the // exact thread state at that time. It could be in MONITOR_WAIT or // in SLEEPING or some other state. // Enqueue a VM_Operation to do the job for us - sometime later // Check if an external suspend request has completed (or has been // cancelled). Returns true if the thread is externally suspended and // The bits parameter returns information about the code path through // the routine. Useful for debugging: // set in is_ext_suspend_completed(): // 0x00000001 - routine was entered // 0x00000010 - routine return false at end // 0x00000100 - thread exited (return false) // 0x00000200 - suspend request cancelled (return false) // 0x00000400 - thread suspended (return true) // 0x00001000 - thread is in a suspend equivalent state (return true) // 0x00002000 - thread is native and walkable (return true) // 0x00004000 - thread is native_trans and walkable (needed retry) // set in wait_for_ext_suspend_completion(): // 0x00010000 - routine was entered // 0x00020000 - suspend request cancelled before loop (return false) // 0x00040000 - thread suspended before loop (return true) // 0x00080000 - suspend request cancelled in loop (return false) // 0x00100000 - thread suspended in loop (return true) // 0x00200000 - suspend not completed during retry loop (return false) // Helper class for tracing suspend wait debug bits. // 0x00000100 indicates that the target thread exited before it could // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and // 0x00080000 each indicate a cancelled suspend request so they don't // count as wait failures either. // By default, don't trace bits for is_ext_suspend_completed() calls. // That trace is very chatty. // If tracing for is_ext_suspend_completed() is enabled, then only // trace calls to it from wait_for_ext_suspend_completion() "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
// Thread is in the process of exiting. This is always checked // first to reduce the risk of dereferencing a freed JavaThread. // Suspend request is cancelled. This is always checked before // is_ext_suspended() to reduce the risk of a rogue resume // confusing the thread that made the suspend request. // Now that we no longer do hard suspends of threads running // native code, the target thread can be changing thread state // while we are in this routine: // _thread_in_native -> _thread_in_native_trans -> _thread_blocked // We save a copy of the thread state as observed at this moment // and make our decision about suspend completeness based on the // copy. This closes the race where the thread state is seen as // _thread_in_native_trans in the if-thread_blocked check, but is // seen as _thread_blocked in if-thread_in_native_trans check. // If the thread's state is _thread_blocked and this blocking // condition is known to be equivalent to a suspend, then we can // consider the thread to be externally suspended. This means that // the code that sets _thread_blocked has been modified to do // self-suspension if the blocking condition releases. We also // used to check for CONDVAR_WAIT here, but that is now covered by // the _thread_blocked with self-suspension check. // Return true since we wouldn't be here unless there was still an // external suspend request. // Threads running native code will self-suspend on native==>VM/Java // transitions. If its stack is walkable (should always be the case // unless this function is called before the actual java_suspend() // call), then the wait is done. // The thread is transitioning from thread_in_native to another // thread state. check_safepoint_and_suspend_for_native_trans() // will force the thread to self-suspend. If it hasn't gotten // there yet we may have caught the thread in-between the native // code check above and the self-suspend. Lucky us. If we were // called by wait_for_ext_suspend_completion(), then it // will be doing the retries so we don't have to. // Since we use the saved thread state in the if-statement above, // there is a chance that the thread has already transitioned to // _thread_blocked by the time we get here. In that case, we will // make a single unnecessary pass through the logic below. This // doesn't hurt anything since we still do the trans retry. // Once the thread leaves thread_in_native_trans for another // thread state, we break out of this retry loop. We shouldn't // need this flag to prevent us from getting back here, but // sometimes paranoia is good. // We wait for the thread to transition to a more usable state. // We used to do an "os::yield_all(i)" call here with the intention // that yielding would increase on each retry. However, the parameter // is ignored on Linux which means the yield didn't scale up. Waiting // on the SR_lock below provides a much more predictable scale up for // the delay. It also provides a simple/direct point to check for any // safepoint requests from the VMThread // temporarily drops SR_lock while doing wait with safepoint check // (if we're a JavaThread - the WatcherThread can also call this) // and increase delay with each retry // check the actual thread state instead of what we saved above // the thread has transitioned to another thread state so // try all the checks (except this one) one more time. // Wait for an external suspend request to complete (or be cancelled). // Returns true if the thread is externally suspended and false otherwise. false /* !called_by_wait */,
bits);
// local flag copies to minimize SR_lock hold time // set a marker so is_ext_suspend_completed() knows we are the caller // We use reset_bits to reinitialize the bits value at the top of // each retry loop. This allows the caller to make use of any // unused bits for their own marking purposes. // must release SR_lock to allow suspension to complete // A cancelled suspend request is the only false return from // is_ext_suspend_completed() that keeps us from entering the for (
int i =
1; i <=
retries; i++) {
// We used to do an "os::yield_all(i)" call here with the intention // that yielding would increase on each retry. However, the parameter // is ignored on Linux which means the yield didn't scale up. Waiting // on the SR_lock below provides a much more predictable scale up for // the delay. It also provides a simple/direct point to check for any // safepoint requests from the VMThread // wait with safepoint check (if we're a JavaThread - the WatcherThread // can also call this) and increase delay with each retry // It is possible for the external suspend request to be cancelled // (by a resume) before the actual suspend operation is completed. // Refresh our local copy to see if we still need to wait. // A cancelled suspend request is the only false return from // is_ext_suspend_completed() that keeps us from staying in the // thread did not suspend after all our retries // This should not need to be atomic as the only way for simultaneous // updates is via interrupts. Even then this should be rare or non-existant // and we don't care that much anyway. // Called by flat profiler // Callers have already called wait_for_ext_suspend_completion // The assertion for that is currently too complex to put here: // self suspension saves needed state. // Note: If clear_interrupted==false, this simply fetches and // returns the value of the field osthread()->interrupted(). "Should only fail when parallel.");
"Should only fail when parallel.");
// Do oop for ThreadShadow // no nmethods in a generic thread... // get_priority assumes osthread initialized // Thread::print_on_error() is called by fatal error handler. Don't use // any lock or allocate memory. // The flag: potential_vm_operation notifies if this particular safepoint state could potential // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that // no threads which allow_vm_block's are held // Check if current thread is allowed to block at a safepoint fatal(
"Possible safepoint reached by thread that does not allow it");
fatal(
"LEAF method calling lock?");
// Make sure we do not hold any locks that the VM thread also uses. // This could potentially lead to deadlocks // Threads_lock is special, since the safepoint synchronization will not start before this is // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock, // since it is used to transfer control between JavaThreads and the VMThread // Do not *exclude* any locks unless you are absolutly sure it is correct. Ask someone else first! cur !=
Compile_lock &&
// Temporary: should not be necessary when we get spearate compilation warning(
"Thread holding lock at safepoint that vm can block on: %s",
cur->
name());
// We could enter a safepoint here and thus have a gc // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being // used for compilation in the future. If that change is made, the need for these methods // should be revisited, and they should be removed if possible. // NOTE: this must be called inside the main thread. // Creates the initial ThreadGroup // Creates the initial Thread // sun.jkernel.DownloadManager may not present in the JDK; just return // java.lang.System class // public static String setProperty(String key, String value); // Thread gets assigned specified name and null target // Thread gets assigned name "Thread-nnn" and null target // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument) // NamedThread -- non-JavaThread subclasses with multiple // uniquely named instances should derive from this. // ======= WatcherThread ======== // The watcher thread exists to simulate timer interrupts. It should // be replaced by an abstraction over whatever native support for // timer interrupts exists on the platform. // Set the watcher thread to the highest OS priority which should not be // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY // is created. The only normal thread using this priority is the reference // handler thread, which runs for very short intervals only. // If the VMThread's priority is not lower than the WatcherThread profiling // Calculate how long it'll be until the next PeriodicTask work // should be done, and sleep that amount of time. // A fatal error has happened, the error handler(VMError::report_and_die) // should abort JVM after creating an error log file. However in some // rare cases, the error handler itself might deadlock. Here we try to // kill JVM if the fatal error handler fails to abort in 2 minutes. // This code is in WatcherThread because WatcherThread wakes up // periodically so the fatal error handler doesn't need to do anything; // also because the WatcherThread is less likely to crash than other os::
sleep(
this,
2 *
60 *
1000,
false);
// Wake up 5 seconds later, the fatal handler may reset OnError or // ShowMessageBoxOnError when it is ready to abort. // If we have no more tasks left due to dynamic disenrollment, // shut down the thread since we don't currently support dynamic enrollment // Signal that it is terminated // Thread destructor usually does this.. // Create the single instance of WatcherThread // it is ok to take late safepoints here, if needed // This wait should make safepoint checks, wait without a timeout, // and wait as a suspend-equivalent condition. // Note: If the FlatProfiler is running, then this thread is waiting // for the WatcherThread to terminate and the WatcherThread, via the // FlatProfiler task, is waiting for the external suspend request on // this thread to complete. wait_for_ext_suspend_completion() will // eventually timeout, but that takes time. Making this wait a // suspend-equivalent condition solves that timeout problem. // ======= JavaThread ======== // A JavaThread is a normal Java thread // Set the claimed par_id to -1 (ie not claiming any par_ids) // This is where we would decide to either give each thread it's own profiler // or use one global one from FlatProfiler, // or up to some count of the number of profiled threads, etc. // Setup safepoint state info for this thread // JVMTI PopFrame support return true;
// Stack already guarded or guard pages not needed. // For those architectures which have separate register and // memory stacks, we must check the register stack to see if // Java code never executes within the yellow zone: the latter is only // there to provoke an exception during stack banging. If java code // is executing there, either StackShadowPages should be larger, or // some exception code in c1, c2 or the interpreter isn't unwinding // _vm_exited is set at safepoint, and Threads_lock is never released // we will block here forever // Remove this ifdef when C1 is ported to the compiler interface. // Create the native thread itself. // The _osthread may be NULL here because we ran out of memory (too many threads active). // We need to throw and OutOfMemoryError - however we cannot do this here because the caller // may hold a lock and all locks must be unlocked before throwing the exception (throwing // the exception consists of creating the exception object & initializing it, initialization // will leave the VM via a JavaCall and then all locks must be unlocked). // The thread is still suspended when we reach here. Thread must be explicit started // by creator! Furthermore, the thread must also explicitly be added to the Threads list // by calling Threads:add. The reason why this is not done here, is because the thread // object must be fully initialized (take a look at JVM_Start) // JSR166 -- return the parker to the free list // Free any remaining previous UnrollBlock // This can only happen if thread is destroyed before deoptimization occurs. // individual jvmtiDeferredLocalVariableSet are CHeapObj's // All Java related clean up happens in exit // The first routine called by a new Java thread // initialize thread-local alloc buffer related fields // used to test validitity of stack trace backs // Record real stack base and size. // Initialize thread local storage; set before calling MutexLocker // Thread is now sufficient initialized to be handled by the safepoint code as being // in the VM. Change thread state from _thread_new to _thread_in_vm // This operation might block. We call that after all safepoint checks for a new thread has // We call another function to do the rest so we are sure that the stack addresses used // from there will be lower than the stack base just computed // Note, thread is no longer valid at this point! // Execute thread entry point. If this thread is being asked to restart, // or has been stopped before starting, do not reexecute entry point. // Note: Due to JVM_StopThread we can have pending exceptions already! // enter the thread's entry point only if we have no pending exceptions // We do not need to grap the Threads_lock, since we are operating on ourself. // Ignore pending exception (ThreadDeath), since we are exiting anyway // It is of profound importance that we set the stillborn bit and reset the thread object, // before we do the notify. Since, changing these two variable will make JVM_IsAlive return // false. So in case another thread is doing a join on this thread , it will detect that the thread // is dead when it gets notified. // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED. // Ignore pending exception (ThreadDeath), since we are exiting anyway // For any new cleanup additions, please check to see if they need to be applied to // cleanup_failed_attach_current_thread as well. // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This // has to be fixed by a runtime query method // JSR-166: change call from from ThreadGroup.uncaughtException to // java.lang.Thread.dispatchUncaughtException Events::
log(
"uncaught exception INTPTR_FORMAT " " INTPTR_FORMAT " " INTPTR_FORMAT",
// Check if the method Thread.dispatchUncaughtException() exists. If so // call it. Otherwise we have an older library without the JSR-166 changes, // so call ThreadGroup.uncaughtException() // Call Thread.exit(). We try 3 times in case we got another Thread.stop during // the execution of the method. If that is not enough, then we don't really care. Thread.stop // We have notified the agents that we are exiting, before we go on, // we must check for a pending external suspend request and honor it // in order to not surprise the thread that made the suspend request. // Things get a little tricky here. We have a pending external // suspend request, but we are holding the SR_lock so we // can't just self-suspend. So we temporarily drop the lock // and then self-suspend. // We're done with this suspend request, but we have to loop around // and check again. Eventually we will get SR_lock without a pending // external suspend request and will be able to mark ourselves as // no more external suspends are allowed at this point // before_exit() has already posted JVMTI THREAD_END events // Notify waiters on thread object. This has to be done after exit() is called // on the thread (if the thread is the last thread in a daemon ThreadGroup the // group should have the destroyed bit set before waiters are notified). // 6282335 JNI DetachCurrentThread spec states that all Java monitors // held by this thread must be released. A detach operation must only // get here if there are no Java frames on the stack. Therefore, any // owned monitors at this point MUST be JNI-acquired monitors which are // pre-inflated and in the monitor cache. // ensure_join() ignores IllegalThreadStateExceptions, and so does this. // These things needs to be done while we are still a Java Thread. Make sure that thread // is in a consistent state, in case GC happens // These have to be removed while this is still a valid thread. // We must flush G1-related buffers before removing a thread from // the list of active threads. // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread // Flush G1-related queues. // Note: this function shouldn't block if it's called in // _thread_in_native_trans state (such as from // check_special_condition_for_native_trans()). // If we are at a polling page safepoint (not a poll return) // then we must defer async exception because live registers // will be clobbered by the exception path. Poll return is // ok because the call we a returning from already collides // with exception handling registers and so there is no issue. // (The exception handling path kills call result registers but // this is ok since the exception kills the result anyway). // if the code we are returning to has deoptimized we must defer // the exception otherwise live registers get clobbered on the // exception path before deoptimization is able to retrieve them. tty->
print_cr(
"deferred async exception at compiled safepoint");
// Conditions have changed since has_special_runtime_exit_condition() // - if we were here only because of an external suspend request, // then that was taken care of above (or cancelled) so we are done // - if we were here because of another async request, then it has // been cleared between the has_special_runtime_exit_condition() // and now so again we are done // Check for pending async. exception // Only overwrite an already pending exception, if it is not a threadDeath. // We cannot call Exceptions::_throw(...) here because we cannot block "must have handled the async condition, if no exception");
// Check for pending external suspend. Internal suspend requests do // not use handle_special_runtime_exit_condition(). // If JNIEnv proxies are allowed, don't self-suspend if the target // thread is not the current thread. In older versions of jdbx, jdbx // threads could call into the VM with another thread's JNIEnv so we // can be here operating on behalf of a suspended thread (4432884). // Because thread is external suspended the safepoint code will count // thread as at a safepoint. This can be odd because we can be here // as _thread_in_Java which would normally transition to _thread_blocked // at a safepoint. We would like to mark the thread as _thread_blocked // before calling java_suspend_self like all other callers of it but // we must then observe proper safepoint protocol. (We can't leave // _thread_blocked with a safepoint in progress). However we can be // here as _thread_in_native_trans so we can't use a normal transition // transition. We could do something like: // JavaThreadState state = thread_state(); // set_thread_state(_thread_in_vm); // ThreadBlockInVM tbivm(this); // set_thread_state(_thread_in_vm_trans); // set_thread_state(state); // but that is pretty messy. Instead we just go with the way the // code has worked before and note that this is the only path to // java_suspend_self that doesn't put the thread in _thread_blocked // We might be here for reasons in addition to the self-suspend request // so check for other async requests. // Do not throw asynchronous exceptions against the compiler thread // (the compiler thread should not be a Java thread -- fix in 1.4.2) // This is a change from JDK 1.1, but JDK 1.2 will also do it: // Actually throw the Throwable against the target Thread - however // only if there is no thread death exception installed already. // If the topmost frame is a runtime stub, then we are calling into // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..) // must deoptimize the caller before continuing, as the compiled exception handler table // BiasedLocking needs an updated RegisterMap for the revoke monitors pass // Set async. pending exception in thread. // for AbortVMOnException flag // Interrupt thread so it will wake up from a potential wait() // External suspension mechanism. // Tell the VM to suspend a thread when ever it knows that it does not hold on // to any VM_locks and it is at a transition // Self-suspension will happen on the transition out of the vm. // Catch "this" coming in from JNIEnv pointers when the thread has been freed // + Target thread will not execute any new bytecode (that's why we need to // + Target thread will not enter any new monitors // a racing resume has cancelled us; bail out now // Warning: is_ext_suspend_completed() may temporarily drop the // SR_lock to allow the thread to reach a stable thread state if // it is currently in a transient thread state. // Part II of external suspension. // A JavaThread self suspends when it detects a pending external suspend // request. This is usually on transitions. It is also done in places // where continuing to the next transition would surprise the caller, // Returns the number of times that the thread self-suspended. // Note: DO NOT call java_suspend_self() when you just want to block current // thread. java_suspend_self() is the second stage of cooperative // suspension for external suspend requests and should only be used // to complete an external suspend request. // we are in the process of exiting so don't suspend "must have walkable stack");
"a thread trying to self-suspend should not already be suspended");
// If we are self-suspending as a result of the lifting of a // suspend equivalent condition, then the suspend_equivalent // flag is not cleared until we set the ext_suspended flag so // that wait_for_ext_suspend_completion() returns consistent // A racing resume may have cancelled us before we grabbed SR_lock // above. Or another external suspend request could be waiting for us // by the time we return from SR_lock()->wait(). The thread // that requested the suspension may already be trying to walk our // stack and if we return now, we can change the stack out from under // it. This would be a "bad thing (TM)" and cause the stack walker // to crash. We stay self-suspended until there are no more pending // external suspend requests. // _ext_suspended flag is cleared by java_resume() // verify the JavaThread has not yet been published in the Threads::list, and // hence doesn't need protection from concurrent access at this stage "java thread shouldn't have been published yet!");
"java thread shouldn't have been published yet!");
// Slow path when the native==>VM/Java barriers detect a safepoint is in // progress or when _suspend_flags is non-zero. // Current thread needs to self-suspend if there is a suspend request and/or // block if a safepoint is in progress. // Async exception ISN'T checked. // Note only the ThreadInVMfromNative transition can call this function // directly and when thread state is _thread_in_native_trans // If JNIEnv proxies are allowed, don't self-suspend if the target // thread is not the current thread. In older versions of jdbx, jdbx // threads could call into the VM with another thread's JNIEnv so we // can be here operating on behalf of a suspended thread (4432884). // We mark this thread_blocked state as a suspend-equivalent so // that a caller to is_ext_suspend_completed() won't be confused. // The suspend-equivalent state is cleared by java_suspend_self(). // If the safepoint code sees the _thread_in_native_trans state, it will // wait until the thread changes to other thread state. There is no // guarantee on how soon we can obtain the SR_lock and complete the // self-suspend request. It would be a bad idea to let safepoint wait for // too long. Temporarily change the state to _thread_blocked to // let the VM thread know that this thread is ready for GC. The problem // of changing thread state is that safepoint could happen just after // java_suspend_self() returns after being resumed, and VM thread will // see the _thread_blocked state. We must check for safepoint // after restoring the state and make sure we won't leave while a safepoint // Make sure new state is seen by VM thread // Force a fence between the write above and read below // Must use this rather than serialization page in particular on Windows // If we are safepointing, then block the caller which may not be // the same as the target thread (see above). // Since we know we're safe to deopt the current state is a safe state fatal(
"missed deoptimization!");
// Slow path when the native==>VM/Java barriers detect a safepoint is in // progress or when _suspend_flags is non-zero. // Current thread needs to self-suspend if there is a suspend request and/or // block if a safepoint is in progress. // Also check for pending async exception (not including unsafe access error). // Note only the native==>VM/Java barriers can call this function and when // thread state is _thread_in_native_trans. // We are in _thread_in_native_trans state, don't handle unsafe // access error since that may block. // We need to guarantee the Threads_lock here, since resumes are not // allowed during safepoint synchronization // Can only resume from an external suspension // Sanity check: thread is gone, has started exiting or the thread // was not externally suspended. // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len); warning(
"Attempt to allocate stack guard pages failed.");
warning(
"Attempt to protect stack guard pages failed.");
warning(
"Attempt to deallocate stack guard pages failed.");
warning(
"Attempt to deallocate stack guard pages failed.");
warning(
"Attempt to unprotect stack guard pages failed.");
// The base notation is from the stacks point of view, growing downward. // We need to adjust it to work correctly with guard_memory() warning(
"Attempt to guard stack yellow zone failed.");
// Simply return if called for a thread that does not use guard pages. // The base notation is from the stacks point of view, growing downward. // We need to adjust it to work correctly with guard_memory() warning(
"Attempt to unguard stack yellow zone failed.");
// The base notation is from the stacks point of view, growing downward. // We need to adjust it to work correctly with guard_memory() warning(
"Attempt to guard stack red zone failed.");
// The base notation is from the stacks point of view, growing downward. // We need to adjust it to work correctly with guard_memory() warning(
"Attempt to unguard stack red zone failed.");
// ignore is there is no stack // traverse the stack frames. Starts from top frame. // Function for testing deoptimization // BiasedLocking needs an updated RegisterMap for the revoke monitors pass bool deopt =
false;
// Dump stack only if a deopt actually happens. // Iterate over all frames in the thread and deoptimize // Deoptimize only at particular bcis. DeoptimizeOnlyAt // consists of comma or carriage return separated numbers so // search for the current bci in that string. // Check that the bci found is bracketed by terminators. deopt =
true;
// One-time only print before deopt // BiasedLocking needs an updated RegisterMap for the revoke monitors pass // Flush deferred store-barriers, if any, associated with // initializing stores done by this JavaThread in the current epoch. // The ThreadProfiler oops_do is done from FlatProfiler::oops_do // since there may be more than one thread using each ThreadProfiler. // Traverse the GCHandles // Traverse the privileged stack // traverse the registered growable array // Traverse the monitor chunks // Traverse the execution stack // callee_target is never live across a gc point so NULL it here should // it still contain a methdOop. // If we have deferred set_locals there might be oops waiting to be // Traverse instance variables at the end since the GC may be moving things // around using this function // Traverse the execution stack default:
return "unknown thread state";
// Called by Threads::print() for VM_PrintThreads operation // print guess for valid stack memory region (assume 4K pages); helps lock debugging // Called by fatal error handler. The difference between this and // JavaThread::print() is that we can't grab lock or allocate memory. // Verify oops in the thread. // Verify the stack frames. // CR 6300358 (sub-CR 2137150) // Most callers of this method assume that it can't return NULL but a // thread may not have a name whilst it is in the process of attaching to // the VM - see CR 6412693, and there are places where a JavaThread can be // seen prior to having it's threadObj set (eg JNI attaching threads and // if vm exit occurs during initialization). These cases can all be accounted // for such that this method never returns NULL. // early safepoints can hit while current thread does not yet have TLS // Current JavaThreads are allowed to get their own name without // Returns a non-NULL representation of this thread's name, or a suitable // descriptive string if there is no set name else if (
is_attaching()) {
// workaround for 6412693 - see 6404306 name_str =
"<no-name - thread is attaching>";
// ThreadGroup.name can be null // ThreadGroup.name can be null // Link Java Thread object <-> C++ Thread // Get the C++ thread object (an oop) from the JNI handle (a jthread) // and put it into a new Handle. The Handle "thread_oop" can then // be used to pass the C++ thread object to other methods. // Set the Java level thread object (jthread) field of the // new thread (a JavaThread *) to C++ thread object using the // Set the thread field (a JavaThread *) of the // oop representing the java_lang_Thread to the new thread (a JavaThread *). // Push the Java priority down to the native thread; needs Threads_lock // Add the new thread to the Threads list and set it in motion. // We must have threads lock in order to call Threads::add. // It is crucial that we do not block before the thread is // added to the Threads list for if a GC happens, then the java_thread oop // will not be visited by GC. // Support for JSR-166 locks // Print out lock information // Ignore non-Java frames // Bail-out case for too deep stacks // JVMTI PopFrame support // Create a CompilerThread // ======= Threads ======== // The Threads class links together all active threads, and provides // operations over all threads. It is protected by its own Mutex // lock, which is also used in other contexts to protect thread // operations from having the thread being operated on from exiting // and going away unexpectedly (e.g., safepoint synchronization) // All JavaThreads + all non-JavaThreads (i.e., every thread in the system) // ALL_JAVA_THREADS iterates through all JavaThreads // Someday we could have a table or list of all non-JavaThreads. // For now, just manually iterate through them. // Strictly speaking, the following NULL check isn't sufficient to make sure // the data for WatcherThread is still valid upon being examined. However, // considering that WatchThread terminates when the VM is on the way to // exit at safepoint, the chance of the above is extremely small. The right // way to prevent termination of WatcherThread would be to acquire // Terminator_lock, but we can't do that without violating the lock rank // checking in some cases. // If CompilerThreads ever become non-JavaThreads, add them here // Initialize the output stream module // Process java launcher properties. // Initialize the os module before using TLS // Initialize system properties. // So that JDK version can be used as a discrimintor when parsing arguments // Record VM creation timing statistics // Timing (must come after argument parsing) // Initialize the os module after parsing the args // Initialize output stream logging // Convert -Xrun to -agentlib: if there is no JVM_OnLoad // Must be before create_vm_init_agents() // Launch -agentlib/-agentpath and converted -Xrun agents // Initialize Threads state // Initialize global data structures and create system classes in heap // Attach the main thread to this os thread // must do this before set_active_handles and initialize_thread_local_storage // Note: on solaris initialize_thread_local_storage() will (indirectly) // change the stack size recorded here to one based on the java thread // stacksize. This adjusted size is what is used to figure the placement "Failed necessary internal allocation. Out of swap space");
*
canTryAgain =
false;
// don't let caller call JNI_CreateJavaVM again // Enable guard page *after* os::create_main_thread(), otherwise it would // Initialize Java-Leve synchronization subsystem // Initialize global modules *
canTryAgain =
false;
// don't let caller call JNI_CreateJavaVM again // Any JVMTI raw monitors entered in onload will transition into // real raw monitor. VM is setup enough here for raw monitor enter. // Wait for the VM thread to become ready, and VMThread::run to initialize // Monitors can have spurious returns, must always check another state flag // At this point, the Universe is initialized, but we have not executed // any byte code. Now is a good time (the only time) to dump out the // internal state of the JVM for sharing. // Always call even when there are not JVMTI environments yet, since environments // may be attached late and JVMTI must track phases of VM execution // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. warning(
"java.lang.String not initialized");
// static final "frontCacheEnabled" field before we start creating instances // Possible we might not find this field; if so, don't break // static final "stringCacheEnabled" field before we start creating instances // Possible that StringValue isn't present: if so, silently don't break // Possible we might not find this field: if so, silently don't break // Initialize java_lang.System (needed before creating the thread) // Set thread status to running since main thread has // been started and running. // The VM preresolve methods to these classes. Make sure that get initialized // The VM creates & returns objects of this class. Make sure it's initialized. warning(
"java.lang.System not initialized");
// an instance of OutOfMemory exception has been allocated earlier warning(
"java.lang.OutOfMemoryError has not been initialized");
warning(
"java.lang.NullPointerException has not been initialized");
warning(
"java.lang.ClassCastException has not been initialized");
warning(
"java.lang.ArrayStoreException has not been initialized");
warning(
"java.lang.ArithmeticException has not been initialized");
warning(
"java.lang.StackOverflowError has not been initialized");
// Background : the static initializer of java.lang.Compiler tries to read // property"java.compiler" and read & write property "java.vm.info". // When a security manager is installed through the command line // option "-Djava.security.manager", the above properties are not // readable and the static initializer for java.lang.Compiler fails // resulting in a NoClassDefFoundError. This can happen in any // user code which calls methods in java.lang.Compiler. // Hack : the hack is to pre-load and initialize this class, so that only // system domains are on the stack when the properties are read. // Currently even the AWT code has calls to methods in java.lang.Compiler. // On the classic VM, java.lang.Compiler is loaded very early to load the JIT. // Future Fix : the best fix is to grant everyone permissions to read "java.compiler" and // read and write"java.vm.info" in the default policy file. See bugid 4211383 // Once that is done, we should remove this hack. // More hackery - the static initializer of java.lang.Compiler adds the string "nojit" to // the java.vm.info property if no jit gets loaded through java.lang.Compiler (the hotspot // compiler does not get loaded through java.lang.Compiler). "java -version" with the // hotspot vm says "nojit" all the time which is confusing. So, we reset it here. // This should also be taken out as soon as 4211383 gets fixed. // Set flag that basic initialization has completed. Used by exceptions and various // debug stuff, that does not work until all basic classes have been initialized. // record VM initialization completion time // Compute system loader. Note that this has to occur after set_init_completed, since // valid exceptions may be thrown in the process. // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and // set_init_completed has just been called, causing exceptions not to be shortcut // anymore. We call vm_exit_during_initialization directly instead. // Support for ConcurrentMarkSweep. This should be cleaned up // and better encapsulated. The ugly nested if test would go away // once things are properly refactored. XXX YSR // Always call even when there are not JVMTI environments yet, since environments // may be attached late and JVMTI must track phases of VM execution // Signal Dispatcher needs to be started before VMInit event is posted // Start Attach Listener if +StartAttachListener or it can't be started lazily // Must be done in the JVMTI live phase so that for backward compatibility the JDWP // back-end can launch with -Xdebug -Xrunjdwp. // Notify JVMTI agents that VM initialization is complete - nop if no agents. // initialize compiler(s) // management agent fails to start possibly due to // configuration problem and is responsible for printing // stack trace if appropriate. Simply exit VM. // Start up the WatcherThread if there are any periodic tasks // NOTE: All PeriodicTasks should be registered by now. If they // aren't, late joiners might appear to start slowly (we might // take a while to process their first tick). // type for the Agent_OnLoad and JVM_OnLoad entry points // Find a command line agent library and return its entry point for // -agentlib: -agentpath: -Xrun // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array. // If we can't find the agent, exit. // Try to load the agent from the standard dll directory // Download instrument dll const char *
fmt =
"%s/bin/java %s -Dkernel.background.download=false" " sun.jkernel.DownloadManager -download client_jvm";
// when this comes back the instrument.dll should be where it belongs. // If we can't find the agent, exit. // Find the OnLoad function. // Find the JVM_OnLoad entry point // Find the Agent_OnLoad entry point // For backwards compatibility with -Xrun // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be // treated like -agentpath: // Must be called before agent libraries are created next =
agent->
next();
// cache the next agent now as this agent may get moved off this list // If there is an JVM_OnLoad function it will get called later, // otherwise see if there is an Agent_OnLoad // switch it to the agent list -- so that Agent_OnLoad will be called, // JVM_OnLoad won't be attempted and Agent_OnUnload will // Create agents for -agentlib: -agentpath: and converted -Xrun // Called very early -- before JavaThreads exist // Invoke the Agent_OnLoad function // Send any Agent_OnUnload notifications // Find the Agent_OnUnload function. // Invoke the Agent_OnUnload function // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries // Invoke the JVM_OnLoad function // We could get here with a pending exception, if so clear it now. // SystemDictionary::resolve_or_null will return null if there was // an exception. If we cannot load the Shutdown class, just don't // call Shutdown.shutdown() at all. This will mean the shutdown hooks // and finalizers (if runFinalizersOnExit is set) won't be run. // Note that if a shutdown hook was registered or runFinalizersOnExit // was called, the Shutdown class would have already been loaded // (Runtime.addShutdownHook and runFinalizersOnExit will load it). // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when // the program falls off the end of main(). Another VM exit path is through // vm_exit() when the program calls System.exit() to return a value or when // there is a serious error in VM. The two shutdown paths are not exactly // the same, but they share Shutdown.shutdown() at Java level and before_exit() // and VM_Exit op at VM level. // + Wait until we are the last non-daemon thread to execute // <-- every thing is still working at this moment --> // shutdown hooks, run finalizers if finalization-on-exit // + Call before_exit(), prepare for VM exit // > run VM level shutdown hooks (they are registered through JVM_OnExit(), // currently the only user of this mechanism is File.deleteOnExit()) // > stop flat profiler, StatSampler, watcher thread, CMS threads, // post thread end and vm death events to JVMTI, // + Call JavaThread::exit(), it will: // > release JNI handle blocks, remove stack guard pages // > remove this thread from Threads list // <-- no more Java code from this thread after this point --> // + Stop VM thread, it will bring the remaining VM to a safepoint and stop // the compiler threads at safepoint // <-- do not use anything that could get blocked by Safepoint --> // + Disable tracing at JNI/JVM barriers // + Set _vm_exited flag for threads that are still running native code // > deletes PerfMemory resources // Wait until we are the last non-daemon thread to execute // This wait should make safepoint checks, wait without a timeout, // and wait as a suspend-equivalent condition. // Note: If the FlatProfiler is running and this thread is waiting // for another non-daemon thread to finish, then the FlatProfiler // is waiting for the external suspend request on this thread to // complete. wait_for_ext_suspend_completion() will eventually // timeout, but that takes time. Making this wait a suspend- // equivalent condition solves that timeout problem. // Hang forever on exit if we are reporting an error. // We are the last thread running, so check if finalizers should be run. // For 1.3 or later this is done in thread->invoke_shutdown_hooks() // run Java level shutdown hooks // 4945125 The vm thread comes to a safepoint during exit. // GC vm_operations can get caught at the safepoint, and the // heap is unparseable if they are caught. Grab the Heap_lock // to prevent this. The GC vm_operations will not be able to // queue until after the vm thread is dead. // clean up ideal graph printers // Now, all Java threads are gone except daemon threads. Daemon threads // running Java code or in VM are stopped by the Safepoint. However, // daemon threads executing native code are still running. But they // will be stopped at native=>Java/VM barriers. Note that we can't // simply kill or suspend them, as it is inherently deadlock-prone. // disable function tracing at JNI/JVM barriers // exit_globals() will delete tty // The threads lock must be owned at this point // Bootstrapping problem: threadObj can be null for initial // JavaThread (or for threads attached via JNI) // Extra scope needed for Thread_lock, so we can check // that we do not remove thread without safepoint code notice // Only one thread left, do a notify on the Threads_lock so a thread waiting // on destroy_vm will wake up. // Make sure that safepoint code disregard this thread. This is needed since // the thread might mess around with locks after this point. This can cause it // to do callbacks into the safepoint code. However, the safepoint code is not aware // of this thread since it is removed from the queue. // Since Events::log uses a lock, we grab it outside the Threads_lock // Threads_lock must be held when this is called (or must be called during a safepoint) // Operations on the Threads list for GC. These are not explicitly locked, // but the garbage collector must provide a safe context for them to run. // In particular, these things should never be called when the Threads_lock // is held by some other thread. (Note: the Safepoint abstraction also // uses the Threads_lock to gurantee this property. It also makes sure that // all threads gets blocked when exiting or starting). // Introduce a mechanism allowing parallel threads to claim threads as // root groups. Overhead should be small enough to use all the time, // even in sequential code. // Used by ParallelScavenge // Get count Java threads that are waiting to enter the specified monitor. "must grab Threads_lock or be at safepoint");
"must grab Threads_lock or be at safepoint");
// NULL owner means not locked so we can skip the search // first, see if owner is the address of a Java thread // If we didn't find a matching Java thread and we didn't force use of // heavyweight monitors, then the owner is the stack address of the // Lock Word in the owning Java thread's stack. // Threads::print_on() is called at safepoint by VM_PrintThreads operation. // Threads::print_on_error() is called by fatal error handler. It's possible // that VM is not at safepoint and/or current thread is inside signal handler. // Don't print stack trace, as the stack may not be walkable. Don't allocate // memory (even in resource area), it might deadlock the error handler. st->
print_cr(
"Java Threads: ( => current thread )");
// Lifecycle management for TSM ParkEvents. // ParkEvents are type-stable (TSM). // In our particular implementation they happen to be immortal. // We manage concurrency on the FreeList with a CAS-based // detach-modify-reattach idiom that avoids the ABA problems // that would otherwise be present in a simple CAS-based // push-pop implementation. (push-one and pop-all) // Caveat: Allocate() and Release() may be called from threads // other than the thread associated with the Event! // If we need to call Allocate() when running as the thread in // question then look for the PD calls to initialize native TLS. // accessed by the associated thread. // See also pd_initialize(). // Note that we could defer associating a ParkEvent with a thread // until the 1st time the thread calls park(). unpark() calls to // an unprovisioned thread would be ignored. The first park() call // for a thread would allocate and associate a ParkEvent and return // In rare cases -- JVM_RawMonitor* operations -- we can find t == null. // Start by trying to recycle an existing but unassociated // ParkEvent from the global free list. // 1: Detach - sequester or privatize the list // Tantamount to ev = Swap (&FreeList, NULL) // We've detached the list. The list in-hand is now // local to this thread. This thread can operate on the // list without risk of interference from other threads. // 2: Extract -- pop the 1st element from the list. // 3: Try to reattach the residual list // New nodes arrived. Try to detach the recent arrivals. // 4: Merge Arv into List // Do this the hard way -- materialize a new ParkEvent. // In rare cases an allocating thread might detach a long list -- // installing null into FreeList -- and then stall or be obstructed. // A 2nd thread calling Allocate() would see FreeList == null. // The list held privately by the 1st thread is unavailable to the 2nd thread. // In that case the 2nd thread would have to materialize a new ParkEvent, // even though free ParkEvents existed in the system. In this case we end up // with more ParkEvents in circulation than we need, but the race is // rare and the outcome is benign. Ideally, the # of extant ParkEvents // is equal to the maximum # of threads that existed at any one time. // Because of the race mentioned above, segments of the freelist // can be transiently inaccessible. At worst we may end up with the // # of ParkEvents in circulation slightly above the ideal. // Note that if we didn't have the TSM/immortal constraint, then // when reattaching, above, we could trim the list. ev->
reset() ;
// courtesy to caller // The mechanism is "half" lock-free. // Override operator new and delete so we can ensure that the // least significant byte of ParkEvent addresses is 0. // Beware that excessive address alignment is undesirable // as it can result in D$ index usage imbalance as // well as bank access imbalance on Niagara-like platforms, // although Niagara's hash function should help. // ParkEvents are type-stable and immortal ... // 6399321 As a temporary measure we copied & modified the ParkEvent:: // allocate() and release() code for use by Parkers. The Parker:: forms // will eventually be removed as we consolide and shift over to ParkEvents // for both builtin synchronization and JSR166 operations. // Start by trying to recycle an existing but unassociated // Parker from the global free list. // Tantamount to p = Swap (&FreeList, NULL) // We've detached the list. The list in-hand is now // local to this thread. This thread can operate on the // list without risk of interference from other threads. // 2: Extract -- pop the 1st element from the list. // 3: Try to reattach the residual list // New nodes arrived. Try to detach the recent arrivals. // 4: Merge Arv into List // Do this the hard way -- materialize a new Parker.. // In rare cases an allocating thread might detach // a long list -- installing null into FreeList --and // then stall. Another thread calling Allocate() would see // FreeList == null and then invoke the ctor. In this case we // end up with more Parkers in circulation than we need, but // the race is rare and the outcome is benign. // Ideally, the # of extant Parkers is equal to the // maximum # of threads that existed at any one time. // Because of the race mentioned above, segments of the // freelist can be transiently inaccessible. At worst // we may end up with the # of Parkers in circulation // slightly above the ideal.