thread.cpp revision 2842
0N/A * Copyright (c) 1997, 2011, Oracle and/or its affiliates. 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. 873N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 567N/A// Only bother with this argument setup if dtrace is available 1008N/A#
else // ndef DTRACE_ENABLED 2086N/A#
endif // ndef DTRACE_ENABLED 3646N/A// - ConcurrentMarkSweepThread 3980N/A// Support for forcing alignment of thread objects for biased locking 3349N/A "JavaThread alignment code overflowed allocated storage");
6158N/A// Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread, 6165N/A // allocated data structures 5713N/A // This initial value ==> never claimed. 5902N/A // the handle mark links itself to last_handle_mark 0N/A // thread-specific hashCode stream generator state - Marsaglia shift-xor form 3853N/A // Many of the following fields are effectively final - immutable 3853N/A // Note that nascent threads can't use the Native Monitor-Mutex 5896N/A // construct until the _MutexEvent is initialized ... 3853N/A // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents 3853N/A // we might instead use a stack of ParkEvents that we could provision on-demand. 0N/A // The stack would act as a cache to avoid calls to ParkEvent::Allocate() 0N/A#
endif // CHECK_UNHANDLED_OOPS 2086N/A "bug in forced alignment of thread objects");
2086N/A // Note: Make sure this method only calls 2086N/A // non-blocking operations. Otherwise, it might not work 2086N/A // During Java thread startup, safepoint code should allow this 2086N/A // method to complete because it may need to allocate memory to 2086N/A // store information for the new thread. 2086N/A // initialize structure dependent on thread local storage 2086N/A // set up any platform-specific state. 2086N/A // Reclaim the objectmonitors from the omFreeList of the moribund thread. 2284N/A // deallocate data structures 2284N/A // since the handle marks are using the handle area, we have to deallocated the root 2086N/A // handle mark before deallocating the thread's handle area, 2086N/A // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads. 2086N/A // We NULL out the fields for good hygiene. 2086N/A // osthread() can be NULL, if creation of thread failed. 2086N/A // clear thread local storage if the Thread is deleting itself 2086N/A // In the case where we're not the current thread, invalidate all the 2086N/A // caches in case some code tries to get the current thread or the 2086N/A // thread that was destroyed, and gets stale information. 2086N/A// NOTE: dummy function for assertion purpose. 3034N/A// Private method to check for dangling thread pointer 4156N/A "possibility of dangling Thread pointer");
5947N/A// Tracing method for basic thread operations 5947N/A // The Threads_lock must be held to get information about 5947N/A // this thread but may not be in some situations when 5947N/A // Start is different from resume in that its safety is guaranteed by context or 5947N/A // being called from a Java method synchronized on the Thread object. 5947N/A // Initialize the thread state to RUNNABLE before starting this thread. 5947N/A // Can not set it after the thread started because we do not know the 5947N/A // exact thread state at that time. It could be in MONITOR_WAIT or 5947N/A // in SLEEPING or some other state. 5947N/A// Enqueue a VM_Operation to do the job for us - sometime later 5947N/A// Check if an external suspend request has completed (or has been 5947N/A// cancelled). Returns true if the thread is externally suspended and 5947N/A// The bits parameter returns information about the code path through 5947N/A// the routine. Useful for debugging: 5947N/A// set in is_ext_suspend_completed(): 5947N/A// 0x00000001 - routine was entered 5947N/A// 0x00000010 - routine return false at end 0N/A// 0x00000100 - thread exited (return false) 6133N/A// 0x00000200 - suspend request cancelled (return false) 0N/A// 0x00000400 - thread suspended (return true) 0N/A// 0x00001000 - thread is in a suspend equivalent state (return true) 2342N/A// 0x00002000 - thread is native and walkable (return true) 1008N/A// 0x00004000 - thread is native_trans and walkable (needed retry) 6238N/A// set in wait_for_ext_suspend_completion(): 6238N/A// 0x00010000 - routine was entered 0N/A// 0x00020000 - suspend request cancelled before loop (return false) 0N/A// 0x00040000 - thread suspended before loop (return true) 0N/A// 0x00080000 - suspend request cancelled in loop (return false) 1177N/A// 0x00100000 - thread suspended in loop (return true) 121N/A// 0x00200000 - suspend not completed during retry loop (return false) 1177N/A// Helper class for tracing suspend wait debug bits. 0N/A// 0x00000100 indicates that the target thread exited before it could 1273N/A// self-suspend which is not a wait failure. 0x00000200, 0x00020000 and 1273N/A// 0x00080000 each indicate a cancelled suspend request so they don't 1273N/A// count as wait failures either. 1273N/A // By default, don't trace bits for is_ext_suspend_completed() calls. 1273N/A // That trace is very chatty. 1273N/A // If tracing for is_ext_suspend_completed() is enabled, then only 1273N/A // trace calls to it from wait_for_ext_suspend_completion() 3381N/A "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
0N/A // Thread is in the process of exiting. This is always checked 0N/A // first to reduce the risk of dereferencing a freed JavaThread. 3349N/A // Suspend request is cancelled. This is always checked before 3349N/A // is_ext_suspended() to reduce the risk of a rogue resume 3349N/A // confusing the thread that made the suspend request. 3853N/A // Now that we no longer do hard suspends of threads running 3853N/A // native code, the target thread can be changing thread state 3853N/A // while we are in this routine: 3853N/A // _thread_in_native -> _thread_in_native_trans -> _thread_blocked 3853N/A // We save a copy of the thread state as observed at this moment 3853N/A // and make our decision about suspend completeness based on the 729N/A // copy. This closes the race where the thread state is seen as 729N/A // _thread_in_native_trans in the if-thread_blocked check, but is 729N/A // seen as _thread_blocked in if-thread_in_native_trans check. 729N/A // If the thread's state is _thread_blocked and this blocking 729N/A // condition is known to be equivalent to a suspend, then we can 729N/A // consider the thread to be externally suspended. This means that 729N/A // the code that sets _thread_blocked has been modified to do 729N/A // self-suspension if the blocking condition releases. We also 729N/A // used to check for CONDVAR_WAIT here, but that is now covered by 729N/A // the _thread_blocked with self-suspension check. 729N/A // Return true since we wouldn't be here unless there was still an 729N/A // external suspend request. 729N/A // Threads running native code will self-suspend on native==>VM/Java 729N/A // transitions. If its stack is walkable (should always be the case 0N/A // unless this function is called before the actual java_suspend() 4274N/A // call), then the wait is done. 4274N/A // The thread is transitioning from thread_in_native to another 4274N/A // thread state. check_safepoint_and_suspend_for_native_trans() 4274N/A // will force the thread to self-suspend. If it hasn't gotten 4274N/A // there yet we may have caught the thread in-between the native 4274N/A // code check above and the self-suspend. Lucky us. If we were 4274N/A // called by wait_for_ext_suspend_completion(), then it 4274N/A // will be doing the retries so we don't have to. 4274N/A // Since we use the saved thread state in the if-statement above, 0N/A // there is a chance that the thread has already transitioned to 1344N/A // _thread_blocked by the time we get here. In that case, we will 1344N/A // make a single unnecessary pass through the logic below. This 1344N/A // doesn't hurt anything since we still do the trans retry. 1344N/A // Once the thread leaves thread_in_native_trans for another 1344N/A // thread state, we break out of this retry loop. We shouldn't 1344N/A // need this flag to prevent us from getting back here, but 1344N/A // sometimes paranoia is good. 1344N/A // We wait for the thread to transition to a more usable state. 109N/A // We used to do an "os::yield_all(i)" call here with the intention 109N/A // that yielding would increase on each retry. However, the parameter 109N/A // is ignored on Linux which means the yield didn't scale up. Waiting 4274N/A // on the SR_lock below provides a much more predictable scale up for 109N/A // safepoint requests from the VMThread 109N/A // temporarily drops SR_lock while doing wait with safepoint check 1344N/A // (if we're a JavaThread - the WatcherThread can also call this) 1344N/A // and increase delay with each retry 1344N/A // check the actual thread state instead of what we saved above 110N/A // the thread has transitioned to another thread state so 109N/A // try all the checks (except this one) one more time. 1344N/A// Wait for an external suspend request to complete (or be cancelled). 1344N/A// Returns true if the thread is externally suspended and false otherwise. 729N/A // local flag copies to minimize SR_lock hold time 729N/A // set a marker so is_ext_suspend_completed() knows we are the caller 729N/A // We use reset_bits to reinitialize the bits value at the top of 0N/A // each retry loop. This allows the caller to make use of any 0N/A // unused bits for their own marking purposes. 2086N/A // must release SR_lock to allow suspension to complete 2086N/A // A cancelled suspend request is the only false return from 2086N/A // is_ext_suspend_completed() that keeps us from entering the 1210N/A // We used to do an "os::yield_all(i)" call here with the intention 567N/A // that yielding would increase on each retry. However, the parameter 567N/A // is ignored on Linux which means the yield didn't scale up. Waiting 3387N/A // on the SR_lock below provides a much more predictable scale up for 3387N/A // safepoint requests from the VMThread 567N/A // wait with safepoint check (if we're a JavaThread - the WatcherThread 563N/A // can also call this) and increase delay with each retry 712N/A // It is possible for the external suspend request to be cancelled 712N/A // (by a resume) before the actual suspend operation is completed. 0N/A // Refresh our local copy to see if we still need to wait. 3381N/A // A cancelled suspend request is the only false return from 3381N/A // is_ext_suspend_completed() that keeps us from staying in the 114N/A // thread did not suspend after all our retries 729N/A // This should not need to be atomic as the only way for simultaneous 4760N/A // updates is via interrupts. Even then this should be rare or non-existant 121N/A // and we don't care that much anyway. 0N/A// Called by flat profiler 4156N/A// Callers have already called wait_for_ext_suspend_completion 4156N/A// The assertion for that is currently too complex to put here: 0N/A // self suspension saves needed state. 0N/A // Note: If clear_interrupted==false, this simply fetches and 1177N/A // returns the value of the field osthread()->interrupted(). 5902N/A "Should only fail when parallel.");
2086N/A "Should only fail when parallel.");
567N/A // no nmethods in a generic thread... 567N/A // get_priority assumes osthread initialized 6238N/A// Thread::print_on_error() is called by fatal error handler. Don't use 2556N/A// any lock or allocate memory. 5058N/A// The flag: potential_vm_operation notifies if this particular safepoint state could potential 3980N/A// invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that 2710N/A// no threads which allow_vm_block's are held 563N/A // Check if current thread is allowed to block at a safepoint 0N/A fatal(
"Possible safepoint reached by thread that does not allow it");
1362N/A // Make sure we do not hold any locks that the VM thread also uses. 1362N/A // This could potentially lead to deadlocks 1362N/A // Threads_lock is special, since the safepoint synchronization will not start before this is 1362N/A // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock, 1362N/A // since it is used to transfer control between JavaThreads and the VMThread 1362N/A // Do not *exclude* any locks unless you are absolutly sure it is correct. Ask someone else first! 563N/A // We could enter a safepoint here and thus have a gc 4156N/A// We had to move these methods here, because vm threads get into ObjectSynchronizer::enter 0N/A// However, there is a note in JavaThread::is_lock_owned() about the VM threads not being 0N/A// used for compilation in the future. If that change is made, the need for these methods 3381N/A// should be revisited, and they should be removed if possible. 2086N/A // NOTE: this must be called inside the main thread. 2033N/A// Creates the initial ThreadGroup 1008N/A// Creates the initial Thread 3214N/A// General purpose hook into Java code, run once when the VM is initialized. 3090N/A// The Java library method itself may be changed independently from the VM. 3214N/A // public static String setProperty(String key, String value); 0N/A // Thread gets assigned specified name and null target 6238N/A // Thread gets assigned name "Thread-nnn" and null target 6318N/A // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument) 3980N/A// NamedThread -- non-JavaThread subclasses with multiple 3980N/A// uniquely named instances should derive from this. 4495N/A// ======= WatcherThread ======== 4495N/A// The watcher thread exists to simulate timer interrupts. It should 4495N/A// be replaced by an abstraction over whatever native support for 4495N/A// timer interrupts exists on the platform. 4495N/A // Set the watcher thread to the highest OS priority which should not be 4495N/A // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY 4495N/A // is created. The only normal thread using this priority is the reference 4495N/A // handler thread, which runs for very short intervals only. 4495N/A // If the VMThread's priority is not lower than the WatcherThread profiling 6174N/A // Calculate how long it'll be until the next PeriodicTask work 0N/A // should be done, and sleep that amount of time. 1008N/A // we expect this to timeout - we only ever get unparked when 6238N/A // spurious wakeup of some kind 6256N/A // A fatal error has happened, the error handler(VMError::report_and_die) 6256N/A // should abort JVM after creating an error log file. However in some 6256N/A // rare cases, the error handler itself might deadlock. Here we try to 6256N/A // kill JVM if the fatal error handler fails to abort in 2 minutes. 6256N/A // This code is in WatcherThread because WatcherThread wakes up 6280N/A // periodically so the fatal error handler doesn't need to do anything; 6256N/A // also because the WatcherThread is less likely to crash than other 920N/A // Wake up 5 seconds later, the fatal handler may reset OnError or 920N/A // ShowMessageBoxOnError when it is ready to abort. 0N/A // If we have no more tasks left due to dynamic disenrollment, 0N/A // shut down the thread since we don't currently support dynamic enrollment 6238N/A // Signal that it is terminated 6374N/A // Thread destructor usually does this.. 3012N/A // Create the single instance of WatcherThread 84N/A // it is ok to take late safepoints here, if needed 6280N/A // This wait should make safepoint checks, wait without a timeout, 6280N/A // and wait as a suspend-equivalent condition. 6280N/A // Note: If the FlatProfiler is running, then this thread is waiting 2556N/A // for the WatcherThread to terminate and the WatcherThread, via the 2556N/A // FlatProfiler task, is waiting for the external suspend request on 2556N/A // this thread to complete. wait_for_ext_suspend_completion() will 2556N/A // eventually timeout, but that takes time. Making this wait a 2556N/A // suspend-equivalent condition solves that timeout problem. 2556N/A// ======= JavaThread ======== 3853N/A// A JavaThread is a normal Java thread 6280N/A // Set the claimed par_id to -1 (ie not claiming any par_ids) 6560N/A // This is where we would decide to either give each thread it's own profiler 6560N/A // or use one global one from FlatProfiler, 6560N/A // or up to some count of the number of profiled threads, etc. 6560N/A // Setup safepoint state info for this thread 6560N/A return true;
// Stack already guarded or guard pages not needed. 6560N/A // For those architectures which have separate register and 6560N/A // memory stacks, we must check the register stack to see if 6560N/A // Java code never executes within the yellow zone: the latter is only 6560N/A // there to provoke an exception during stack banging. If java code 6560N/A // is executing there, either StackShadowPages should be larger, or 6561N/A // some exception code in c1, c2 or the interpreter isn't unwinding 6131N/A // _vm_exited is set at safepoint, and Threads_lock is never released 3069N/A // we will block here forever 3069N/A// Remove this ifdef when C1 is ported to the compiler interface. 6521N/A // Create the native thread itself. 6521N/A // The _osthread may be NULL here because we ran out of memory (too many threads active). 6521N/A // We need to throw and OutOfMemoryError - however we cannot do this here because the caller 6521N/A // may hold a lock and all locks must be unlocked before throwing the exception (throwing 6521N/A // the exception consists of creating the exception object & initializing it, initialization 6521N/A // will leave the VM via a JavaCall and then all locks must be unlocked). 6521N/A // The thread is still suspended when we reach here. Thread must be explicit started 6521N/A // by creator! Furthermore, the thread must also explicitly be added to the Threads list 6521N/A // by calling Threads:add. The reason why this is not done here, is because the thread 6647N/A // object must be fully initialized (take a look at JVM_Start) 3069N/A // JSR166 -- return the parker to the free list 3079N/A // Free any remaining previous UnrollBlock 6642N/A // This can only happen if thread is destroyed before deoptimization occurs. 6521N/A // individual jvmtiDeferredLocalVariableSet are CHeapObj's 3069N/A // All Java related clean up happens in exit 6238N/A// The first routine called by a new Java thread 6238N/A // initialize thread-local alloc buffer related fields 6238N/A // used to test validitity of stack trace backs 6238N/A // Record real stack base and size. 6238N/A // Initialize thread local storage; set before calling MutexLocker 6238N/A // Thread is now sufficient initialized to be handled by the safepoint code as being 6238N/A // in the VM. Change thread state from _thread_new to _thread_in_vm 6238N/A // This operation might block. We call that after all safepoint checks for a new thread has 6642N/A // We call another function to do the rest so we are sure that the stack addresses used 6642N/A // from there will be lower than the stack base just computed 6238N/A // Note, thread is no longer valid at this point! 6642N/A // Execute thread entry point unless this thread has a pending exception 6238N/A // or has been stopped before starting. 6642N/A // Note: Due to JVM_StopThread we can have pending exceptions already! 6647N/A // We do not need to grap the Threads_lock, since we are operating on ourself. 6647N/A // Ignore pending exception (ThreadDeath), since we are exiting anyway 6647N/A // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED. 6647N/A // Clear the native thread instance - this makes isAlive return false and allows the join() 6647N/A // to complete once we've done the notify_all below 6647N/A // Ignore pending exception (ThreadDeath), since we are exiting anyway 0N/A// For any new cleanup additions, please check to see if they need to be applied to 0N/A// cleanup_failed_attach_current_thread as well. 3000N/A // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place 0N/A // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This 0N/A // has to be fixed by a runtime query method 0N/A // JSR-166: change call from from ThreadGroup.uncaughtException to 0N/A // java.lang.Thread.dispatchUncaughtException 3058N/A Events::
log(
"uncaught exception INTPTR_FORMAT " " INTPTR_FORMAT " " INTPTR_FORMAT",
4495N/A // Check if the method Thread.dispatchUncaughtException() exists. If so 4495N/A // call it. Otherwise we have an older library without the JSR-166 changes, 4495N/A // so call ThreadGroup.uncaughtException() 2528N/A "\nException: %s thrown from the UncaughtExceptionHandler" 1527N/A // Call Thread.exit(). We try 3 times in case we got another Thread.stop during 0N/A // the execution of the method. If that is not enough, then we don't really care. Thread.stop 2896N/A // We have notified the agents that we are exiting, before we go on, 2900N/A // we must check for a pending external suspend request and honor it 2900N/A // in order to not surprise the thread that made the suspend request. 2896N/A // Things get a little tricky here. We have a pending external 2900N/A // suspend request, but we are holding the SR_lock so we 3853N/A // can't just self-suspend. So we temporarily drop the lock 2896N/A // We're done with this suspend request, but we have to loop around 2900N/A // and check again. Eventually we will get SR_lock without a pending 2900N/A // external suspend request and will be able to mark ourselves as 2896N/A // no more external suspends are allowed at this point 2900N/A // before_exit() has already posted JVMTI THREAD_END events 2900N/A // Notify waiters on thread object. This has to be done after exit() is called 2900N/A // on the thread (if the thread is the last thread in a daemon ThreadGroup the 2900N/A // group should have the destroyed bit set before waiters are notified). 2900N/A // 6282335 JNI DetachCurrentThread spec states that all Java monitors 6140N/A // held by this thread must be released. A detach operation must only 2900N/A // get here if there are no Java frames on the stack. Therefore, any 2900N/A // owned monitors at this point MUST be JNI-acquired monitors which are 2900N/A // pre-inflated and in the monitor cache. 2900N/A // ensure_join() ignores IllegalThreadStateExceptions, and so does this. 2900N/A // These things needs to be done while we are still a Java Thread. Make sure that thread 2900N/A // is in a consistent state, in case GC happens 2896N/A // These have to be removed while this is still a valid thread. 2896N/A // We must flush G1-related buffers before removing a thread from 2896N/A // the list of active threads. 2900N/A // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread 4235N/A "we should not be at a safepoint");
121N/A // The SATB queue should have been constructed with its active 0N/A // If we are creating the thread during a marking cycle, we should 0N/A // set the active field of the SATB queue to true. 0N/A // The dirty card queue should have been constructed with its 1527N/A // active field set to true. 3083N/A // These have to be removed while this is still a valid thread. 675N/A// Note: this function shouldn't block if it's called in 675N/A// _thread_in_native_trans state (such as from 675N/A// check_special_condition_for_native_trans()). 675N/A // If we are at a polling page safepoint (not a poll return) 675N/A // then we must defer async exception because live registers 675N/A // will be clobbered by the exception path. Poll return is 675N/A // ok because the call we a returning from already collides 1559N/A // with exception handling registers and so there is no issue. 2123N/A // (The exception handling path kills call result registers but 1559N/A // this is ok since the exception kills the result anyway). 1559N/A // if the code we are returning to has deoptimized we must defer 1559N/A // the exception otherwise live registers get clobbered on the 1559N/A // exception path before deoptimization is able to retrieve them. 1559N/A // Conditions have changed since has_special_runtime_exit_condition() 1559N/A // - if we were here only because of an external suspend request, 1559N/A // then that was taken care of above (or cancelled) so we are done 1559N/A // - if we were here because of another async request, then it has 1559N/A // been cleared between the has_special_runtime_exit_condition() 675N/A // and now so again we are done 675N/A // Check for pending async. exception 675N/A // Only overwrite an already pending exception, if it is not a threadDeath. 675N/A // We cannot call Exceptions::_throw(...) here because we cannot block 712N/A "must have handled the async condition, if no exception");
0N/A // Check for pending external suspend. Internal suspend requests do 0N/A // not use handle_special_runtime_exit_condition(). 1177N/A // If JNIEnv proxies are allowed, don't self-suspend if the target 1177N/A // thread is not the current thread. In older versions of jdbx, jdbx 675N/A // threads could call into the VM with another thread's JNIEnv so we 675N/A // can be here operating on behalf of a suspended thread (4432884). 675N/A // Because thread is external suspended the safepoint code will count 675N/A // thread as at a safepoint. This can be odd because we can be here 21N/A // as _thread_in_Java which would normally transition to _thread_blocked 675N/A // at a safepoint. We would like to mark the thread as _thread_blocked 675N/A // before calling java_suspend_self like all other callers of it but 675N/A // we must then observe proper safepoint protocol. (We can't leave 675N/A // _thread_blocked with a safepoint in progress). However we can be 675N/A // here as _thread_in_native_trans so we can't use a normal transition 699N/A // transition. We could do something like: 699N/A // JavaThreadState state = thread_state(); 699N/A // set_thread_state(_thread_in_vm); 699N/A // ThreadBlockInVM tbivm(this); 675N/A // set_thread_state(_thread_in_vm_trans); 675N/A // if (safepoint) block; 1849N/A // set_thread_state(state); 1849N/A // but that is pretty messy. Instead we just go with the way the 1849N/A // code has worked before and note that this is the only path to 1849N/A // java_suspend_self that doesn't put the thread in _thread_blocked 1849N/A // We might be here for reasons in addition to the self-suspend request 1849N/A // so check for other async requests. 675N/A // Do not throw asynchronous exceptions against the compiler thread 675N/A // (the compiler thread should not be a Java thread -- fix in 1.4.2) 712N/A // Actually throw the Throwable against the target Thread - however 699N/A // only if there is no thread death exception installed already. 1849N/A // If the topmost frame is a runtime stub, then we are calling into 675N/A // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..) 712N/A // must deoptimize the caller before continuing, as the compiled exception handler table 21N/A // may not be valid 185N/A // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 318N/A // Set async. pending exception in thread. 712N/A // for AbortVMOnException flag 21N/A // Interrupt thread so it will wake up from a potential wait() 121N/A// External suspension mechanism. 5037N/A// Tell the VM to suspend a thread when ever it knows that it does not hold on 5044N/A// to any VM_locks and it is at a transition 5037N/A// Self-suspension will happen on the transition out of the vm. 5037N/A// Catch "this" coming in from JNIEnv pointers when the thread has been freed 5037N/A// + Target thread will not execute any new bytecode (that's why we need to 5037N/A// + Target thread will not enter any new monitors 699N/A // a racing resume has cancelled us; bail out now 318N/A // Warning: is_ext_suspend_completed() may temporarily drop the 318N/A // SR_lock to allow the thread to reach a stable thread state if 712N/A // it is currently in a transient thread state. 2342N/A// Part II of external suspension. 2342N/A// A JavaThread self suspends when it detects a pending external suspend 2342N/A// request. This is usually on transitions. It is also done in places 2342N/A// where continuing to the next transition would surprise the caller, 2342N/A// Returns the number of times that the thread self-suspended. 2342N/A// Note: DO NOT call java_suspend_self() when you just want to block current 2342N/A// thread. java_suspend_self() is the second stage of cooperative 2342N/A// suspension for external suspend requests and should only be used 2342N/A// to complete an external suspend request. 2342N/A // we are in the process of exiting so don't suspend 2392N/A "must have walkable stack");
2342N/A "a thread trying to self-suspend should not already be suspended");
2342N/A // If we are self-suspending as a result of the lifting of a 2342N/A // suspend equivalent condition, then the suspend_equivalent 2342N/A // flag is not cleared until we set the ext_suspended flag so 2342N/A // that wait_for_ext_suspend_completion() returns consistent 2342N/A // A racing resume may have cancelled us before we grabbed SR_lock 2342N/A // above. Or another external suspend request could be waiting for us 2342N/A // by the time we return from SR_lock()->wait(). The thread 2342N/A // that requested the suspension may already be trying to walk our 2342N/A // stack and if we return now, we can change the stack out from under 712N/A // it. This would be a "bad thing (TM)" and cause the stack walker 712N/A // to crash. We stay self-suspended until there are no more pending 712N/A // external suspend requests. 902N/A // _ext_suspended flag is cleared by java_resume() 2342N/A// verify the JavaThread has not yet been published in the Threads::list, and 902N/A// hence doesn't need protection from concurrent access at this stage 1666N/A "java thread shouldn't have been published yet!");
712N/A "java thread shouldn't have been published yet!");
712N/A// Slow path when the native==>VM/Java barriers detect a safepoint is in 712N/A// progress or when _suspend_flags is non-zero. 984N/A// Current thread needs to self-suspend if there is a suspend request and/or 712N/A// block if a safepoint is in progress. 712N/A// Async exception ISN'T checked. 712N/A// Note only the ThreadInVMfromNative transition can call this function 1666N/A// directly and when thread state is _thread_in_native_trans 712N/A // If JNIEnv proxies are allowed, don't self-suspend if the target 712N/A // thread is not the current thread. In older versions of jdbx, jdbx 712N/A // threads could call into the VM with another thread's JNIEnv so we 1177N/A // can be here operating on behalf of a suspended thread (4432884). 712N/A // We mark this thread_blocked state as a suspend-equivalent so 5037N/A // that a caller to is_ext_suspend_completed() won't be confused. 712N/A // The suspend-equivalent state is cleared by java_suspend_self(). 0N/A // If the safepoint code sees the _thread_in_native_trans state, it will 0N/A // wait until the thread changes to other thread state. There is no 0N/A // guarantee on how soon we can obtain the SR_lock and complete the 0N/A // self-suspend request. It would be a bad idea to let safepoint wait for 0N/A // too long. Temporarily change the state to _thread_blocked to 0N/A // let the VM thread know that this thread is ready for GC. The problem 0N/A // of changing thread state is that safepoint could happen just after 0N/A // java_suspend_self() returns after being resumed, and VM thread will 185N/A // see the _thread_blocked state. We must check for safepoint 161N/A // after restoring the state and make sure we won't leave while a safepoint 503N/A // Make sure new state is seen by VM thread 2342N/A // Force a fence between the write above and read below 2342N/A // Must use this rather than serialization page in particular on Windows 2342N/A // If we are safepointing, then block the caller which may not be 2342N/A // the same as the target thread (see above). 3538N/A// Slow path when the native==>VM/Java barriers detect a safepoint is in 3538N/A// progress or when _suspend_flags is non-zero. 902N/A// Current thread needs to self-suspend if there is a suspend request and/or 3538N/A// block if a safepoint is in progress. 902N/A// Also check for pending async exception (not including unsafe access error). 902N/A// Note only the native==>VM/Java barriers can call this function and when 902N/A// thread state is _thread_in_native_trans. 2342N/A // We are in _thread_in_native_trans state, don't handle unsafe 2342N/A // access error since that may block. 2342N/A// We need to guarantee the Threads_lock here, since resumes are not 2342N/A// allowed during safepoint synchronization 2342N/A// Can only resume from an external suspension 2556N/A // Sanity check: thread is gone, has started exiting or the thread 2556N/A // was not externally suspended. 2342N/A // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len); 712N/A warning(
"Attempt to deallocate stack guard pages failed.");
151N/A warning(
"Attempt to deallocate stack guard pages failed.");
0N/A warning(
"Attempt to unprotect stack guard pages failed.");
3381N/A // The base notation is from the stacks point of view, growing downward. 3349N/A // We need to adjust it to work correctly with guard_memory() 2342N/A // Simply return if called for a thread that does not use guard pages. 2342N/A // The base notation is from the stacks point of view, growing downward. 6158N/A // We need to adjust it to work correctly with guard_memory() 1960N/A // The base notation is from the stacks point of view, growing downward. 712N/A // We need to adjust it to work correctly with guard_memory() 42N/A // The base notation is from the stacks point of view, growing downward. 121N/A // We need to adjust it to work correctly with guard_memory() 0N/A warning(
"Attempt to unguard stack red zone failed.");
984N/A // ignore is there is no stack 984N/A // traverse the stack frames. Starts from top frame. 1177N/A// Function for testing deoptimization 21N/A // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 0N/A bool deopt =
false;
// Dump stack only if a deopt actually happens. 0N/A // Iterate over all frames in the thread and deoptimize 0N/A // Deoptimize only at particular bcis. DeoptimizeOnlyAt 0N/A // consists of comma or carriage return separated numbers so 0N/A // search for the current bci in that string. 2086N/A // Check that the bci found is bracketed by terminators. 233N/A // it is a Java nmethod 1238N/A // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 5058N/A// If the caller is a NamedThread, then remember, in the current scope, 5058N/A// the given JavaThread in its _processed_thread field. 1008N/A // Verify that the deferred card marks have been flushed. 1008N/A // The ThreadProfiler oops_do is done from FlatProfiler::oops_do 1008N/A // since there may be more than one thread using each ThreadProfiler. 5607N/A // Record JavaThread to GC thread 5058N/A // Traverse the privileged stack 1008N/A // traverse the registered growable array 5607N/A // Traverse the monitor chunks 1008N/A // Traverse the execution stack 5058N/A // callee_target is never live across a gc point so NULL it here should 1530N/A // it still contain a methdOop. 1140N/A // If we have deferred set_locals there might be oops waiting to be 5607N/A // Traverse instance variables at the end since the GC may be moving things 5058N/A // around using this function 1008N/A // Traverse the execution stack 1395N/A default:
return "unknown thread state";
1008N/A// Called by Threads::print() for VM_PrintThreads operation 1008N/A // print guess for valid stack memory region (assume 4K pages); helps lock debugging 1008N/A// Called by fatal error handler. The difference between this and 1008N/A// JavaThread::print() is that we can't grab lock or allocate memory. 3381N/A // Verify oops in the thread. 4009N/A // Verify the stack frames. 3381N/A// CR 6300358 (sub-CR 2137150) 3349N/A// Most callers of this method assume that it can't return NULL but a 3381N/A// thread may not have a name whilst it is in the process of attaching to 3349N/A// the VM - see CR 6412693, and there are places where a JavaThread can be 3349N/A// seen prior to having it's threadObj set (eg JNI attaching threads and 3349N/A// if vm exit occurs during initialization). These cases can all be accounted 3349N/A// for such that this method never returns NULL. 3381N/A // early safepoints can hit while current thread does not yet have TLS 3349N/A // Current JavaThreads are allowed to get their own name without 3381N/A// Returns a non-NULL representation of this thread's name, or a suitable 3349N/A// descriptive string if there is no set name 6238N/A // ThreadGroup.name can be null 3853N/A // ThreadGroup.name can be null 3349N/A // Link Java Thread object <-> C++ Thread 3349N/A // Get the C++ thread object (an oop) from the JNI handle (a jthread) 3381N/A // and put it into a new Handle. The Handle "thread_oop" can then 3349N/A // be used to pass the C++ thread object to other methods. 3349N/A // Set the Java level thread object (jthread) field of the 3349N/A // new thread (a JavaThread *) to C++ thread object using the 3349N/A // Set the thread field (a JavaThread *) of the 3349N/A // oop representing the java_lang_Thread to the new thread (a JavaThread *). 6133N/A // Push the Java priority down to the native thread; needs Threads_lock 6133N/A // Add the new thread to the Threads list and set it in motion. 6133N/A // We must have threads lock in order to call Threads::add. 6133N/A // It is crucial that we do not block before the thread is 6133N/A // added to the Threads list for if a GC happens, then the java_thread oop 6133N/A // will not be visited by GC. 6133N/A // Support for JSR-166 locks 5306N/A // Print out lock information // Ignore non-Java frames // Bail-out case for too deep stacks // JVMTI PopFrame support // Print our all the locations that contain oops and whether they are // valid or not. This useful when trying to find the oldest frame // where an oop has gone bad since the frame walk is from youngest to // Print or validate the layout of stack frames // Create a CompilerThread // Safepoints can occur when the sweeper is scanning an nmethod so // process it here to make sure it isn't unloaded in the middle of // ======= 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-Level synchronization subsystem // Initialize global modules *
canTryAgain =
false;
// don't let caller call JNI_CreateJavaVM again // Should be done after the heap is fully created // 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. // The Java side of PostVMInitHook.run must deal with all // exceptions and provide means of diagnosis. // 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). // Give os specific code one last chance to start // 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. const char *
msg =
"Could not find agent library ";
const char *
sub_msg =
" in absolute path, with error: ";
// 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. const char *
sub_msg =
" on the library path, with error: ";
// 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. // After this point, we'll never emerge out of the safepoint before // the VM exits, so concurrent GC threads do not need to be explicitly // stopped; they remain inactive until the process exits. // Note: some concurrent G1 threads may be running during a safepoint, // but these will not be accessing the heap, just some G1-specific side // data structures that are not accessed by any other threads but them // after this point in a terminal safepoint. // 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 // See the comment for this method in thread.hpp for its purpose and // why it is called here. // 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 )");
// Internal SpinLock and Mutex // Ad-hoc mutual exclusion primitives: SpinLock and Mux // We employ SpinLocks _only for low-contention, fixed-length // short-duration critical sections where we're concerned // about native mutex_t or HotSpot Mutex:: latency. // The mux construct provides a spin-then-block mutual exclusion // Testing has shown that contention on the ListLock guarding gFreeList // is common. If we implement ListLock as a simple SpinLock it's common // for the JVM to devolve to yielding with little progress. This is true // despite the fact that the critical sections protected by ListLock are // TODO-FIXME: ListLock should be of type SpinLock. // We should make this a 1st-class type, integrated into the lock // hierarchy as leaf-locks. Critically, the SpinLock structure // should have sufficient padding to avoid false-sharing and excessive // cache-coherency traffic. return ;
// normal fast-path return // Slow-path : We've encountered contention -- Spin/Yield/Block strategy. // Consider using a simple NakedSleep() instead. // Then SpinAcquire could be called by non-JVM threads // Roach-motel semantics. // It's safe if subsequent LDs and STs float "up" into the critical section, // but prior LDs and STs within the critical section can't be allowed // to reorder or float past the ST that releases the lock. // muxAcquire and muxRelease: // * muxAcquire and muxRelease support a single-word lock-word construct. // The LSB of the word is set IFF the lock is held. // The remainder of the word points to the head of a singly-linked list // of threads blocked on the lock. // * The current implementation of muxAcquire-muxRelease uses its own // dedicated Thread._MuxEvent instance. If we're interested in // minimizing the peak number of extant ParkEvent instances then // we could eliminate _MuxEvent and "borrow" _ParkEvent as long // as certain invariants were satisfied. Specifically, care would need // to be taken with regards to consuming unpark() "permits". // A safe rule of thumb is that a thread would never call muxAcquire() // if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently // park(). Otherwise the _ParkEvent park() operation in muxAcquire() could // consume an unpark() permit intended for monitorenter, for instance. // One way around this would be to widen the restricted-range semaphore // implemented in park(). Another alternative would be to provide // multiple instances of the PlatformEvent() for each thread. One // instance would be dedicated to muxAcquire-muxRelease, for instance. // -- for short-term locking only as muxAcquire does not perform // thread state transitions. // * We could implement muxAcquire and muxRelease with MCS or CLH locks // but with parking or spin-then-park instead of pure spinning. // * Use Taura-Oyama-Yonenzawa locks. // * It's possible to construct a 1-0 lock if we encode the lockword as // (List,LockByte). Acquire will CAS the full lockword while Release // will STB 0 into the LockByte. The 1-0 scheme admits stranding, so // acquiring threads use timers (ParkTimed) to detect and recover from // the stranding window. Thread/Node structures must be aligned on 256-byte // boundaries by using placement-new. // * Augment MCS with advisory back-link fields maintained with CAS(). // Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner. // The validity of the backlinks must be ratified before we trust the value. // If the backlinks are invalid the exiting thread must back-track through the // the forward links, which are always trustworthy. // * Add a successor indication. The LockWord is currently encoded as // (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable // to provide the usual futile-wakeup optimization. // See RTStt for details. // * Consider schedctl.sc_nopreempt to cover the critical section. // Optional spin phase: spin-then-park strategy // The following fence() isn't _strictly necessary as the subsequent // CAS() both serializes execution and ratifies the fetched *Lock value. Self->
OnList = 0 ;
// hygiene - allows stronger asserts continue ;
// Interference -- *Lock changed -- Just retry // Optional spin phase: spin-then-park strategy // The following fence() isn't _strictly necessary as the subsequent // CAS() both serializes execution and ratifies the fetched *Lock value. // We call ::Release while holding the outer lock, thus // artificially lengthening the critical section. // Consider deferring the ::Release() until the subsequent unlock(), // after we've dropped the outer lock. continue ;
// Interference -- *Lock changed -- Just retry // Release() must extract a successor from the list and then wake that thread. // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme // similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list. // (B) Extract a successor from the private list "in-hand" // (C) attempt to CAS() the residual back into *Lock over null. // If there were any newly arrived threads and the CAS() would fail. // In that case Release() would detach the RATs, re-merge the list in-hand // with the RATs and repeat as needed. Alternately, Release() might // detach and extract a successor, but then pass the residual list to the wakee. // The wakee would be responsible for reattaching and remerging before it // competed for the lock. // Both "pop" and DMR are immune from ABA corruption -- there can be // multiple concurrent pushers, but only one popper or detacher. // This implementation pops from the head of the list. This is unfair, // but tends to provide excellent throughput as hot threads remain hot. // (We wake recently run threads first). // The following CAS() releases the lock and pops the head element.