aoqi@0: /* aoqi@0: * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. aoqi@0: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. aoqi@0: * aoqi@0: * This code is free software; you can redistribute it and/or modify it aoqi@0: * under the terms of the GNU General Public License version 2 only, as aoqi@0: * published by the Free Software Foundation. aoqi@0: * aoqi@0: * This code is distributed in the hope that it will be useful, but WITHOUT aoqi@0: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or aoqi@0: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License aoqi@0: * version 2 for more details (a copy is included in the LICENSE file that aoqi@0: * accompanied this code). aoqi@0: * aoqi@0: * You should have received a copy of the GNU General Public License version aoqi@0: * 2 along with this work; if not, write to the Free Software Foundation, aoqi@0: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. aoqi@0: * aoqi@0: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA aoqi@0: * or visit www.oracle.com if you need additional information or have any aoqi@0: * questions. aoqi@0: * aoqi@0: */ aoqi@0: aoqi@0: #include "precompiled.hpp" aoqi@0: #include "classfile/symbolTable.hpp" aoqi@0: #include "classfile/systemDictionary.hpp" aoqi@0: #include "code/codeCache.hpp" aoqi@0: #include "code/icBuffer.hpp" aoqi@0: #include "code/nmethod.hpp" aoqi@0: #include "code/pcDesc.hpp" aoqi@0: #include "code/scopeDesc.hpp" aoqi@0: #include "gc_interface/collectedHeap.hpp" aoqi@0: #include "interpreter/interpreter.hpp" aoqi@0: #include "memory/resourceArea.hpp" aoqi@0: #include "memory/universe.inline.hpp" aoqi@0: #include "oops/oop.inline.hpp" aoqi@0: #include "oops/symbol.hpp" aoqi@0: #include "runtime/compilationPolicy.hpp" aoqi@0: #include "runtime/deoptimization.hpp" aoqi@0: #include "runtime/frame.inline.hpp" aoqi@0: #include "runtime/interfaceSupport.hpp" aoqi@0: #include "runtime/mutexLocker.hpp" aoqi@0: #include "runtime/osThread.hpp" aoqi@0: #include "runtime/safepoint.hpp" aoqi@0: #include "runtime/signature.hpp" aoqi@0: #include "runtime/stubCodeGenerator.hpp" aoqi@0: #include "runtime/stubRoutines.hpp" aoqi@0: #include "runtime/sweeper.hpp" aoqi@0: #include "runtime/synchronizer.hpp" aoqi@0: #include "runtime/thread.inline.hpp" aoqi@0: #include "services/memTracker.hpp" aoqi@0: #include "services/runtimeService.hpp" aoqi@0: #include "utilities/events.hpp" aoqi@0: #include "utilities/macros.hpp" aoqi@0: #ifdef TARGET_ARCH_x86 aoqi@0: # include "nativeInst_x86.hpp" aoqi@0: # include "vmreg_x86.inline.hpp" aoqi@0: #endif aoqi@0: #ifdef TARGET_ARCH_sparc aoqi@0: # include "nativeInst_sparc.hpp" aoqi@0: # include "vmreg_sparc.inline.hpp" aoqi@0: #endif aoqi@0: #ifdef TARGET_ARCH_zero aoqi@0: # include "nativeInst_zero.hpp" aoqi@0: # include "vmreg_zero.inline.hpp" aoqi@0: #endif aoqi@0: #ifdef TARGET_ARCH_arm aoqi@0: # include "nativeInst_arm.hpp" aoqi@0: # include "vmreg_arm.inline.hpp" aoqi@0: #endif aoqi@0: #ifdef TARGET_ARCH_ppc aoqi@0: # include "nativeInst_ppc.hpp" aoqi@0: # include "vmreg_ppc.inline.hpp" aoqi@0: #endif aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp" aoqi@0: #include "gc_implementation/shared/concurrentGCThread.hpp" aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: #ifdef COMPILER1 aoqi@0: #include "c1/c1_globals.hpp" aoqi@0: #endif aoqi@0: aoqi@0: PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC aoqi@0: aoqi@0: // -------------------------------------------------------------------------------------------------- aoqi@0: // Implementation of Safepoint begin/end aoqi@0: aoqi@0: SafepointSynchronize::SynchronizeState volatile SafepointSynchronize::_state = SafepointSynchronize::_not_synchronized; aoqi@0: volatile int SafepointSynchronize::_waiting_to_block = 0; aoqi@0: volatile int SafepointSynchronize::_safepoint_counter = 0; aoqi@0: int SafepointSynchronize::_current_jni_active_count = 0; aoqi@0: long SafepointSynchronize::_end_of_last_safepoint = 0; aoqi@0: static volatile int PageArmed = 0 ; // safepoint polling page is RO|RW vs PROT_NONE aoqi@0: static volatile int TryingToBlock = 0 ; // proximate value -- for advisory use only aoqi@0: static bool timeout_error_printed = false; aoqi@0: aoqi@0: // Roll all threads forward to a safepoint and suspend them all aoqi@0: void SafepointSynchronize::begin() { aoqi@0: aoqi@0: Thread* myThread = Thread::current(); aoqi@0: assert(myThread->is_VM_thread(), "Only VM thread may execute a safepoint"); aoqi@0: aoqi@0: if (PrintSafepointStatistics || PrintSafepointStatisticsTimeout > 0) { aoqi@0: _safepoint_begin_time = os::javaTimeNanos(); aoqi@0: _ts_of_current_safepoint = tty->time_stamp().seconds(); aoqi@0: } aoqi@0: aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: if (UseConcMarkSweepGC) { aoqi@0: // In the future we should investigate whether CMS can use the aoqi@0: // more-general mechanism below. DLD (01/05). aoqi@0: ConcurrentMarkSweepThread::synchronize(false); aoqi@0: } else if (UseG1GC) { aoqi@0: ConcurrentGCThread::safepoint_synchronize(); aoqi@0: } aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: aoqi@0: // By getting the Threads_lock, we assure that no threads are about to start or aoqi@0: // exit. It is released again in SafepointSynchronize::end(). aoqi@0: Threads_lock->lock(); aoqi@0: aoqi@0: assert( _state == _not_synchronized, "trying to safepoint synchronize with wrong state"); aoqi@0: aoqi@0: int nof_threads = Threads::number_of_threads(); aoqi@0: aoqi@0: if (TraceSafepoint) { aoqi@0: tty->print_cr("Safepoint synchronization initiated. (%d)", nof_threads); aoqi@0: } aoqi@0: aoqi@0: RuntimeService::record_safepoint_begin(); aoqi@0: aoqi@0: MutexLocker mu(Safepoint_lock); aoqi@0: aoqi@0: // Reset the count of active JNI critical threads aoqi@0: _current_jni_active_count = 0; aoqi@0: aoqi@0: // Set number of threads to wait for, before we initiate the callbacks aoqi@0: _waiting_to_block = nof_threads; aoqi@0: TryingToBlock = 0 ; aoqi@0: int still_running = nof_threads; aoqi@0: aoqi@0: // Save the starting time, so that it can be compared to see if this has taken aoqi@0: // too long to complete. aoqi@0: jlong safepoint_limit_time; aoqi@0: timeout_error_printed = false; aoqi@0: aoqi@0: // PrintSafepointStatisticsTimeout can be specified separately. When aoqi@0: // specified, PrintSafepointStatistics will be set to true in aoqi@0: // deferred_initialize_stat method. The initialization has to be done aoqi@0: // early enough to avoid any races. See bug 6880029 for details. aoqi@0: if (PrintSafepointStatistics || PrintSafepointStatisticsTimeout > 0) { aoqi@0: deferred_initialize_stat(); aoqi@0: } aoqi@0: aoqi@0: // Begin the process of bringing the system to a safepoint. aoqi@0: // Java threads can be in several different states and are aoqi@0: // stopped by different mechanisms: aoqi@0: // aoqi@0: // 1. Running interpreted aoqi@0: // The interpeter dispatch table is changed to force it to aoqi@0: // check for a safepoint condition between bytecodes. aoqi@0: // 2. Running in native code aoqi@0: // When returning from the native code, a Java thread must check aoqi@0: // the safepoint _state to see if we must block. If the aoqi@0: // VM thread sees a Java thread in native, it does aoqi@0: // not wait for this thread to block. The order of the memory aoqi@0: // writes and reads of both the safepoint state and the Java aoqi@0: // threads state is critical. In order to guarantee that the aoqi@0: // memory writes are serialized with respect to each other, aoqi@0: // the VM thread issues a memory barrier instruction aoqi@0: // (on MP systems). In order to avoid the overhead of issuing aoqi@0: // a memory barrier for each Java thread making native calls, each Java aoqi@0: // thread performs a write to a single memory page after changing aoqi@0: // the thread state. The VM thread performs a sequence of aoqi@0: // mprotect OS calls which forces all previous writes from all aoqi@0: // Java threads to be serialized. This is done in the aoqi@0: // os::serialize_thread_states() call. This has proven to be aoqi@0: // much more efficient than executing a membar instruction aoqi@0: // on every call to native code. aoqi@0: // 3. Running compiled Code aoqi@0: // Compiled code reads a global (Safepoint Polling) page that aoqi@0: // is set to fault if we are trying to get to a safepoint. aoqi@0: // 4. Blocked aoqi@0: // A thread which is blocked will not be allowed to return from the aoqi@0: // block condition until the safepoint operation is complete. aoqi@0: // 5. In VM or Transitioning between states aoqi@0: // If a Java thread is currently running in the VM or transitioning aoqi@0: // between states, the safepointing code will wait for the thread to aoqi@0: // block itself when it attempts transitions to a new state. aoqi@0: // aoqi@0: _state = _synchronizing; aoqi@0: OrderAccess::fence(); aoqi@0: aoqi@0: // Flush all thread states to memory aoqi@0: if (!UseMembar) { aoqi@0: os::serialize_thread_states(); aoqi@0: } aoqi@0: aoqi@0: // Make interpreter safepoint aware aoqi@0: Interpreter::notice_safepoints(); aoqi@0: aoqi@0: if (UseCompilerSafepoints && DeferPollingPageLoopCount < 0) { aoqi@0: // Make polling safepoint aware aoqi@0: guarantee (PageArmed == 0, "invariant") ; aoqi@0: PageArmed = 1 ; aoqi@0: os::make_polling_page_unreadable(); aoqi@0: } aoqi@0: aoqi@0: // Consider using active_processor_count() ... but that call is expensive. aoqi@0: int ncpus = os::processor_count() ; aoqi@0: aoqi@0: #ifdef ASSERT aoqi@0: for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) { aoqi@0: assert(cur->safepoint_state()->is_running(), "Illegal initial state"); aoqi@0: // Clear the visited flag to ensure that the critical counts are collected properly. aoqi@0: cur->set_visited_for_critical_count(false); aoqi@0: } aoqi@0: #endif // ASSERT aoqi@0: aoqi@0: if (SafepointTimeout) aoqi@0: safepoint_limit_time = os::javaTimeNanos() + (jlong)SafepointTimeoutDelay * MICROUNITS; aoqi@0: aoqi@0: // Iterate through all threads until it have been determined how to stop them all at a safepoint aoqi@0: unsigned int iterations = 0; aoqi@0: int steps = 0 ; aoqi@0: while(still_running > 0) { aoqi@0: for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) { aoqi@0: assert(!cur->is_ConcurrentGC_thread(), "A concurrent GC thread is unexpectly being suspended"); aoqi@0: ThreadSafepointState *cur_state = cur->safepoint_state(); aoqi@0: if (cur_state->is_running()) { aoqi@0: cur_state->examine_state_of_thread(); aoqi@0: if (!cur_state->is_running()) { aoqi@0: still_running--; aoqi@0: // consider adjusting steps downward: aoqi@0: // steps = 0 aoqi@0: // steps -= NNN aoqi@0: // steps >>= 1 aoqi@0: // steps = MIN(steps, 2000-100) aoqi@0: // if (iterations != 0) steps -= NNN aoqi@0: } aoqi@0: if (TraceSafepoint && Verbose) cur_state->print(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: if (PrintSafepointStatistics && iterations == 0) { aoqi@0: begin_statistics(nof_threads, still_running); aoqi@0: } aoqi@0: aoqi@0: if (still_running > 0) { aoqi@0: // Check for if it takes to long aoqi@0: if (SafepointTimeout && safepoint_limit_time < os::javaTimeNanos()) { aoqi@0: print_safepoint_timeout(_spinning_timeout); aoqi@0: } aoqi@0: aoqi@0: // Spin to avoid context switching. aoqi@0: // There's a tension between allowing the mutators to run (and rendezvous) aoqi@0: // vs spinning. As the VM thread spins, wasting cycles, it consumes CPU that aoqi@0: // a mutator might otherwise use profitably to reach a safepoint. Excessive aoqi@0: // spinning by the VM thread on a saturated system can increase rendezvous latency. aoqi@0: // Blocking or yielding incur their own penalties in the form of context switching aoqi@0: // and the resultant loss of $ residency. aoqi@0: // aoqi@0: // Further complicating matters is that yield() does not work as naively expected aoqi@0: // on many platforms -- yield() does not guarantee that any other ready threads aoqi@0: // will run. As such we revert yield_all() after some number of iterations. aoqi@0: // Yield_all() is implemented as a short unconditional sleep on some platforms. aoqi@0: // Typical operating systems round a "short" sleep period up to 10 msecs, so sleeping aoqi@0: // can actually increase the time it takes the VM thread to detect that a system-wide aoqi@0: // stop-the-world safepoint has been reached. In a pathological scenario such as that aoqi@0: // described in CR6415670 the VMthread may sleep just before the mutator(s) become safe. aoqi@0: // In that case the mutators will be stalled waiting for the safepoint to complete and the aoqi@0: // the VMthread will be sleeping, waiting for the mutators to rendezvous. The VMthread aoqi@0: // will eventually wake up and detect that all mutators are safe, at which point aoqi@0: // we'll again make progress. aoqi@0: // aoqi@0: // Beware too that that the VMThread typically runs at elevated priority. aoqi@0: // Its default priority is higher than the default mutator priority. aoqi@0: // Obviously, this complicates spinning. aoqi@0: // aoqi@0: // Note too that on Windows XP SwitchThreadTo() has quite different behavior than Sleep(0). aoqi@0: // Sleep(0) will _not yield to lower priority threads, while SwitchThreadTo() will. aoqi@0: // aoqi@0: // See the comments in synchronizer.cpp for additional remarks on spinning. aoqi@0: // aoqi@0: // In the future we might: aoqi@0: // 1. Modify the safepoint scheme to avoid potentally unbounded spinning. aoqi@0: // This is tricky as the path used by a thread exiting the JVM (say on aoqi@0: // on JNI call-out) simply stores into its state field. The burden aoqi@0: // is placed on the VM thread, which must poll (spin). aoqi@0: // 2. Find something useful to do while spinning. If the safepoint is GC-related aoqi@0: // we might aggressively scan the stacks of threads that are already safe. aoqi@0: // 3. Use Solaris schedctl to examine the state of the still-running mutators. aoqi@0: // If all the mutators are ONPROC there's no reason to sleep or yield. aoqi@0: // 4. YieldTo() any still-running mutators that are ready but OFFPROC. aoqi@0: // 5. Check system saturation. If the system is not fully saturated then aoqi@0: // simply spin and avoid sleep/yield. aoqi@0: // 6. As still-running mutators rendezvous they could unpark the sleeping aoqi@0: // VMthread. This works well for still-running mutators that become aoqi@0: // safe. The VMthread must still poll for mutators that call-out. aoqi@0: // 7. Drive the policy on time-since-begin instead of iterations. aoqi@0: // 8. Consider making the spin duration a function of the # of CPUs: aoqi@0: // Spin = (((ncpus-1) * M) + K) + F(still_running) aoqi@0: // Alternately, instead of counting iterations of the outer loop aoqi@0: // we could count the # of threads visited in the inner loop, above. aoqi@0: // 9. On windows consider using the return value from SwitchThreadTo() aoqi@0: // to drive subsequent spin/SwitchThreadTo()/Sleep(N) decisions. aoqi@0: aoqi@0: if (UseCompilerSafepoints && int(iterations) == DeferPollingPageLoopCount) { aoqi@0: guarantee (PageArmed == 0, "invariant") ; aoqi@0: PageArmed = 1 ; aoqi@0: os::make_polling_page_unreadable(); aoqi@0: } aoqi@0: aoqi@0: // Instead of (ncpus > 1) consider either (still_running < (ncpus + EPSILON)) or aoqi@0: // ((still_running + _waiting_to_block - TryingToBlock)) < ncpus) aoqi@0: ++steps ; aoqi@0: if (ncpus > 1 && steps < SafepointSpinBeforeYield) { aoqi@0: SpinPause() ; // MP-Polite spin aoqi@0: } else aoqi@0: if (steps < DeferThrSuspendLoopCount) { aoqi@0: os::NakedYield() ; aoqi@0: } else { aoqi@0: os::yield_all(steps) ; aoqi@0: // Alternately, the VM thread could transiently depress its scheduling priority or aoqi@0: // transiently increase the priority of the tardy mutator(s). aoqi@0: } aoqi@0: aoqi@0: iterations ++ ; aoqi@0: } aoqi@0: assert(iterations < (uint)max_jint, "We have been iterating in the safepoint loop too long"); aoqi@0: } aoqi@0: assert(still_running == 0, "sanity check"); aoqi@0: aoqi@0: if (PrintSafepointStatistics) { aoqi@0: update_statistics_on_spin_end(); aoqi@0: } aoqi@0: aoqi@0: // wait until all threads are stopped aoqi@0: while (_waiting_to_block > 0) { aoqi@0: if (TraceSafepoint) tty->print_cr("Waiting for %d thread(s) to block", _waiting_to_block); aoqi@0: if (!SafepointTimeout || timeout_error_printed) { aoqi@0: Safepoint_lock->wait(true); // true, means with no safepoint checks aoqi@0: } else { aoqi@0: // Compute remaining time aoqi@0: jlong remaining_time = safepoint_limit_time - os::javaTimeNanos(); aoqi@0: aoqi@0: // If there is no remaining time, then there is an error aoqi@0: if (remaining_time < 0 || Safepoint_lock->wait(true, remaining_time / MICROUNITS)) { aoqi@0: print_safepoint_timeout(_blocking_timeout); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: assert(_waiting_to_block == 0, "sanity check"); aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: if (SafepointTimeout) { aoqi@0: jlong current_time = os::javaTimeNanos(); aoqi@0: if (safepoint_limit_time < current_time) { aoqi@0: tty->print_cr("# SafepointSynchronize: Finished after " aoqi@0: INT64_FORMAT_W(6) " ms", aoqi@0: ((current_time - safepoint_limit_time) / MICROUNITS + aoqi@0: SafepointTimeoutDelay)); aoqi@0: } aoqi@0: } aoqi@0: #endif aoqi@0: aoqi@0: assert((_safepoint_counter & 0x1) == 0, "must be even"); aoqi@0: assert(Threads_lock->owned_by_self(), "must hold Threads_lock"); aoqi@0: _safepoint_counter ++; aoqi@0: aoqi@0: // Record state aoqi@0: _state = _synchronized; aoqi@0: aoqi@0: OrderAccess::fence(); aoqi@0: aoqi@0: #ifdef ASSERT aoqi@0: for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) { aoqi@0: // make sure all the threads were visited aoqi@0: assert(cur->was_visited_for_critical_count(), "missed a thread"); aoqi@0: } aoqi@0: #endif // ASSERT aoqi@0: aoqi@0: // Update the count of active JNI critical regions aoqi@0: GC_locker::set_jni_lock_count(_current_jni_active_count); aoqi@0: aoqi@0: if (TraceSafepoint) { aoqi@0: VM_Operation *op = VMThread::vm_operation(); aoqi@0: tty->print_cr("Entering safepoint region: %s", (op != NULL) ? op->name() : "no vm operation"); aoqi@0: } aoqi@0: aoqi@0: RuntimeService::record_safepoint_synchronized(); aoqi@0: if (PrintSafepointStatistics) { aoqi@0: update_statistics_on_sync_end(os::javaTimeNanos()); aoqi@0: } aoqi@0: aoqi@0: // Call stuff that needs to be run when a safepoint is just about to be completed aoqi@0: do_cleanup_tasks(); aoqi@0: aoqi@0: if (PrintSafepointStatistics) { aoqi@0: // Record how much time spend on the above cleanup tasks aoqi@0: update_statistics_on_cleanup_end(os::javaTimeNanos()); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // Wake up all threads, so they are ready to resume execution after the safepoint aoqi@0: // operation has been carried out aoqi@0: void SafepointSynchronize::end() { aoqi@0: aoqi@0: assert(Threads_lock->owned_by_self(), "must hold Threads_lock"); aoqi@0: assert((_safepoint_counter & 0x1) == 1, "must be odd"); aoqi@0: _safepoint_counter ++; aoqi@0: // memory fence isn't required here since an odd _safepoint_counter aoqi@0: // value can do no harm and a fence is issued below anyway. aoqi@0: aoqi@0: DEBUG_ONLY(Thread* myThread = Thread::current();) aoqi@0: assert(myThread->is_VM_thread(), "Only VM thread can execute a safepoint"); aoqi@0: aoqi@0: if (PrintSafepointStatistics) { aoqi@0: end_statistics(os::javaTimeNanos()); aoqi@0: } aoqi@0: aoqi@0: #ifdef ASSERT aoqi@0: // A pending_exception cannot be installed during a safepoint. The threads aoqi@0: // may install an async exception after they come back from a safepoint into aoqi@0: // pending_exception after they unblock. But that should happen later. aoqi@0: for(JavaThread *cur = Threads::first(); cur; cur = cur->next()) { aoqi@0: assert (!(cur->has_pending_exception() && aoqi@0: cur->safepoint_state()->is_at_poll_safepoint()), aoqi@0: "safepoint installed a pending exception"); aoqi@0: } aoqi@0: #endif // ASSERT aoqi@0: aoqi@0: if (PageArmed) { aoqi@0: // Make polling safepoint aware aoqi@0: os::make_polling_page_readable(); aoqi@0: PageArmed = 0 ; aoqi@0: } aoqi@0: aoqi@0: // Remove safepoint check from interpreter aoqi@0: Interpreter::ignore_safepoints(); aoqi@0: aoqi@0: { aoqi@0: MutexLocker mu(Safepoint_lock); aoqi@0: aoqi@0: assert(_state == _synchronized, "must be synchronized before ending safepoint synchronization"); aoqi@0: aoqi@0: // Set to not synchronized, so the threads will not go into the signal_thread_blocked method aoqi@0: // when they get restarted. aoqi@0: _state = _not_synchronized; aoqi@0: OrderAccess::fence(); aoqi@0: aoqi@0: if (TraceSafepoint) { aoqi@0: tty->print_cr("Leaving safepoint region"); aoqi@0: } aoqi@0: aoqi@0: // Start suspended threads aoqi@0: for(JavaThread *current = Threads::first(); current; current = current->next()) { aoqi@0: // A problem occurring on Solaris is when attempting to restart threads aoqi@0: // the first #cpus - 1 go well, but then the VMThread is preempted when we get aoqi@0: // to the next one (since it has been running the longest). We then have aoqi@0: // to wait for a cpu to become available before we can continue restarting aoqi@0: // threads. aoqi@0: // FIXME: This causes the performance of the VM to degrade when active and with aoqi@0: // large numbers of threads. Apparently this is due to the synchronous nature aoqi@0: // of suspending threads. aoqi@0: // aoqi@0: // TODO-FIXME: the comments above are vestigial and no longer apply. aoqi@0: // Furthermore, using solaris' schedctl in this particular context confers no benefit aoqi@0: if (VMThreadHintNoPreempt) { aoqi@0: os::hint_no_preempt(); aoqi@0: } aoqi@0: ThreadSafepointState* cur_state = current->safepoint_state(); aoqi@0: assert(cur_state->type() != ThreadSafepointState::_running, "Thread not suspended at safepoint"); aoqi@0: cur_state->restart(); aoqi@0: assert(cur_state->is_running(), "safepoint state has not been reset"); aoqi@0: } aoqi@0: aoqi@0: RuntimeService::record_safepoint_end(); aoqi@0: aoqi@0: // Release threads lock, so threads can be created/destroyed again. It will also starts all threads aoqi@0: // blocked in signal_thread_blocked aoqi@0: Threads_lock->unlock(); aoqi@0: aoqi@0: } aoqi@0: #if INCLUDE_ALL_GCS aoqi@0: // If there are any concurrent GC threads resume them. aoqi@0: if (UseConcMarkSweepGC) { aoqi@0: ConcurrentMarkSweepThread::desynchronize(false); aoqi@0: } else if (UseG1GC) { aoqi@0: ConcurrentGCThread::safepoint_desynchronize(); aoqi@0: } aoqi@0: #endif // INCLUDE_ALL_GCS aoqi@0: // record this time so VMThread can keep track how much time has elasped aoqi@0: // since last safepoint. aoqi@0: _end_of_last_safepoint = os::javaTimeMillis(); aoqi@0: } aoqi@0: aoqi@0: bool SafepointSynchronize::is_cleanup_needed() { aoqi@0: // Need a safepoint if some inline cache buffers is non-empty aoqi@0: if (!InlineCacheBuffer::is_empty()) return true; aoqi@0: return false; aoqi@0: } aoqi@0: aoqi@0: aoqi@0: aoqi@0: // Various cleaning tasks that should be done periodically at safepoints aoqi@0: void SafepointSynchronize::do_cleanup_tasks() { aoqi@0: { aoqi@0: TraceTime t1("deflating idle monitors", TraceSafepointCleanupTime); aoqi@0: ObjectSynchronizer::deflate_idle_monitors(); aoqi@0: } aoqi@0: aoqi@0: { aoqi@0: TraceTime t2("updating inline caches", TraceSafepointCleanupTime); aoqi@0: InlineCacheBuffer::update_inline_caches(); aoqi@0: } aoqi@0: { aoqi@0: TraceTime t3("compilation policy safepoint handler", TraceSafepointCleanupTime); aoqi@0: CompilationPolicy::policy()->do_safepoint_work(); aoqi@0: } aoqi@0: aoqi@0: { aoqi@0: TraceTime t4("mark nmethods", TraceSafepointCleanupTime); aoqi@0: NMethodSweeper::mark_active_nmethods(); aoqi@0: } aoqi@0: aoqi@0: if (SymbolTable::needs_rehashing()) { aoqi@0: TraceTime t5("rehashing symbol table", TraceSafepointCleanupTime); aoqi@0: SymbolTable::rehash_table(); aoqi@0: } aoqi@0: aoqi@0: if (StringTable::needs_rehashing()) { aoqi@0: TraceTime t6("rehashing string table", TraceSafepointCleanupTime); aoqi@0: StringTable::rehash_table(); aoqi@0: } aoqi@0: aoqi@0: // rotate log files? aoqi@0: if (UseGCLogFileRotation) { aoqi@0: gclog_or_tty->rotate_log(false); aoqi@0: } aoqi@0: aoqi@0: { aoqi@0: // CMS delays purging the CLDG until the beginning of the next safepoint and to aoqi@0: // make sure concurrent sweep is done aoqi@0: TraceTime t7("purging class loader data graph", TraceSafepointCleanupTime); aoqi@0: ClassLoaderDataGraph::purge_if_needed(); aoqi@0: } aoqi@0: aoqi@0: if (MemTracker::is_on()) { aoqi@0: MemTracker::sync(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: bool SafepointSynchronize::safepoint_safe(JavaThread *thread, JavaThreadState state) { aoqi@0: switch(state) { aoqi@0: case _thread_in_native: aoqi@0: // native threads are safe if they have no java stack or have walkable stack aoqi@0: return !thread->has_last_Java_frame() || thread->frame_anchor()->walkable(); aoqi@0: aoqi@0: // blocked threads should have already have walkable stack aoqi@0: case _thread_blocked: aoqi@0: assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "blocked and not walkable"); aoqi@0: return true; aoqi@0: aoqi@0: default: aoqi@0: return false; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // See if the thread is running inside a lazy critical native and aoqi@0: // update the thread critical count if so. Also set a suspend flag to aoqi@0: // cause the native wrapper to return into the JVM to do the unlock aoqi@0: // once the native finishes. aoqi@0: void SafepointSynchronize::check_for_lazy_critical_native(JavaThread *thread, JavaThreadState state) { aoqi@0: if (state == _thread_in_native && aoqi@0: thread->has_last_Java_frame() && aoqi@0: thread->frame_anchor()->walkable()) { aoqi@0: // This thread might be in a critical native nmethod so look at aoqi@0: // the top of the stack and increment the critical count if it aoqi@0: // is. aoqi@0: frame wrapper_frame = thread->last_frame(); aoqi@0: CodeBlob* stub_cb = wrapper_frame.cb(); aoqi@0: if (stub_cb != NULL && aoqi@0: stub_cb->is_nmethod() && aoqi@0: stub_cb->as_nmethod_or_null()->is_lazy_critical_native()) { aoqi@0: // A thread could potentially be in a critical native across aoqi@0: // more than one safepoint, so only update the critical state on aoqi@0: // the first one. When it returns it will perform the unlock. aoqi@0: if (!thread->do_critical_native_unlock()) { aoqi@0: #ifdef ASSERT aoqi@0: if (!thread->in_critical()) { aoqi@0: GC_locker::increment_debug_jni_lock_count(); aoqi@0: } aoqi@0: #endif aoqi@0: thread->enter_critical(); aoqi@0: // Make sure the native wrapper calls back on return to aoqi@0: // perform the needed critical unlock. aoqi@0: thread->set_critical_native_unlock(); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: aoqi@0: // ------------------------------------------------------------------------------------------------------- aoqi@0: // Implementation of Safepoint callback point aoqi@0: aoqi@0: void SafepointSynchronize::block(JavaThread *thread) { aoqi@0: assert(thread != NULL, "thread must be set"); aoqi@0: assert(thread->is_Java_thread(), "not a Java thread"); aoqi@0: aoqi@0: // Threads shouldn't block if they are in the middle of printing, but... aoqi@0: ttyLocker::break_tty_lock_for_safepoint(os::current_thread_id()); aoqi@0: aoqi@0: // Only bail from the block() call if the thread is gone from the aoqi@0: // thread list; starting to exit should still block. aoqi@0: if (thread->is_terminated()) { aoqi@0: // block current thread if we come here from native code when VM is gone aoqi@0: thread->block_if_vm_exited(); aoqi@0: aoqi@0: // otherwise do nothing aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: JavaThreadState state = thread->thread_state(); aoqi@0: thread->frame_anchor()->make_walkable(thread); aoqi@0: aoqi@0: // Check that we have a valid thread_state at this point aoqi@0: switch(state) { aoqi@0: case _thread_in_vm_trans: aoqi@0: case _thread_in_Java: // From compiled code aoqi@0: aoqi@0: // We are highly likely to block on the Safepoint_lock. In order to avoid blocking in this case, aoqi@0: // we pretend we are still in the VM. aoqi@0: thread->set_thread_state(_thread_in_vm); aoqi@0: aoqi@0: if (is_synchronizing()) { aoqi@0: Atomic::inc (&TryingToBlock) ; aoqi@0: } aoqi@0: aoqi@0: // We will always be holding the Safepoint_lock when we are examine the state aoqi@0: // of a thread. Hence, the instructions between the Safepoint_lock->lock() and aoqi@0: // Safepoint_lock->unlock() are happening atomic with regards to the safepoint code aoqi@0: Safepoint_lock->lock_without_safepoint_check(); aoqi@0: if (is_synchronizing()) { aoqi@0: // Decrement the number of threads to wait for and signal vm thread aoqi@0: assert(_waiting_to_block > 0, "sanity check"); aoqi@0: _waiting_to_block--; aoqi@0: thread->safepoint_state()->set_has_called_back(true); aoqi@0: aoqi@0: DEBUG_ONLY(thread->set_visited_for_critical_count(true)); aoqi@0: if (thread->in_critical()) { aoqi@0: // Notice that this thread is in a critical section aoqi@0: increment_jni_active_count(); aoqi@0: } aoqi@0: aoqi@0: // Consider (_waiting_to_block < 2) to pipeline the wakeup of the VM thread aoqi@0: if (_waiting_to_block == 0) { aoqi@0: Safepoint_lock->notify_all(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // We transition the thread to state _thread_blocked here, but aoqi@0: // we can't do our usual check for external suspension and then aoqi@0: // self-suspend after the lock_without_safepoint_check() call aoqi@0: // below because we are often called during transitions while aoqi@0: // we hold different locks. That would leave us suspended while aoqi@0: // holding a resource which results in deadlocks. aoqi@0: thread->set_thread_state(_thread_blocked); aoqi@0: Safepoint_lock->unlock(); aoqi@0: aoqi@0: // We now try to acquire the threads lock. Since this lock is hold by the VM thread during aoqi@0: // the entire safepoint, the threads will all line up here during the safepoint. aoqi@0: Threads_lock->lock_without_safepoint_check(); aoqi@0: // restore original state. This is important if the thread comes from compiled code, so it aoqi@0: // will continue to execute with the _thread_in_Java state. aoqi@0: thread->set_thread_state(state); aoqi@0: Threads_lock->unlock(); aoqi@0: break; aoqi@0: aoqi@0: case _thread_in_native_trans: aoqi@0: case _thread_blocked_trans: aoqi@0: case _thread_new_trans: aoqi@0: if (thread->safepoint_state()->type() == ThreadSafepointState::_call_back) { aoqi@0: thread->print_thread_state(); aoqi@0: fatal("Deadlock in safepoint code. " aoqi@0: "Should have called back to the VM before blocking."); aoqi@0: } aoqi@0: aoqi@0: // We transition the thread to state _thread_blocked here, but aoqi@0: // we can't do our usual check for external suspension and then aoqi@0: // self-suspend after the lock_without_safepoint_check() call aoqi@0: // below because we are often called during transitions while aoqi@0: // we hold different locks. That would leave us suspended while aoqi@0: // holding a resource which results in deadlocks. aoqi@0: thread->set_thread_state(_thread_blocked); aoqi@0: aoqi@0: // It is not safe to suspend a thread if we discover it is in _thread_in_native_trans. Hence, aoqi@0: // the safepoint code might still be waiting for it to block. We need to change the state here, aoqi@0: // so it can see that it is at a safepoint. aoqi@0: aoqi@0: // Block until the safepoint operation is completed. aoqi@0: Threads_lock->lock_without_safepoint_check(); aoqi@0: aoqi@0: // Restore state aoqi@0: thread->set_thread_state(state); aoqi@0: aoqi@0: Threads_lock->unlock(); aoqi@0: break; aoqi@0: aoqi@0: default: aoqi@0: fatal(err_msg("Illegal threadstate encountered: %d", state)); aoqi@0: } aoqi@0: aoqi@0: // Check for pending. async. exceptions or suspends - except if the aoqi@0: // thread was blocked inside the VM. has_special_runtime_exit_condition() aoqi@0: // is called last since it grabs a lock and we only want to do that when aoqi@0: // we must. aoqi@0: // aoqi@0: // Note: we never deliver an async exception at a polling point as the aoqi@0: // compiler may not have an exception handler for it. The polling aoqi@0: // code will notice the async and deoptimize and the exception will aoqi@0: // be delivered. (Polling at a return point is ok though). Sure is aoqi@0: // a lot of bother for a deprecated feature... aoqi@0: // aoqi@0: // We don't deliver an async exception if the thread state is aoqi@0: // _thread_in_native_trans so JNI functions won't be called with aoqi@0: // a surprising pending exception. If the thread state is going back to java, aoqi@0: // async exception is checked in check_special_condition_for_native_trans(). aoqi@0: aoqi@0: if (state != _thread_blocked_trans && aoqi@0: state != _thread_in_vm_trans && aoqi@0: thread->has_special_runtime_exit_condition()) { aoqi@0: thread->handle_special_runtime_exit_condition( aoqi@0: !thread->is_at_poll_safepoint() && (state != _thread_in_native_trans)); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // ------------------------------------------------------------------------------------------------------ aoqi@0: // Exception handlers aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: aoqi@0: #ifdef SPARC aoqi@0: aoqi@0: #ifdef _LP64 aoqi@0: #define PTR_PAD "" aoqi@0: #else aoqi@0: #define PTR_PAD " " aoqi@0: #endif aoqi@0: aoqi@0: static void print_ptrs(intptr_t oldptr, intptr_t newptr, bool wasoop) { aoqi@0: bool is_oop = newptr ? (cast_to_oop(newptr))->is_oop() : false; aoqi@0: tty->print_cr(PTR_FORMAT PTR_PAD " %s %c " PTR_FORMAT PTR_PAD " %s %s", aoqi@0: oldptr, wasoop?"oop":" ", oldptr == newptr ? ' ' : '!', aoqi@0: newptr, is_oop?"oop":" ", (wasoop && !is_oop) ? "STALE" : ((wasoop==false&&is_oop==false&&oldptr !=newptr)?"STOMP":" ")); aoqi@0: } aoqi@0: aoqi@0: static void print_longs(jlong oldptr, jlong newptr, bool wasoop) { aoqi@0: bool is_oop = newptr ? (cast_to_oop(newptr))->is_oop() : false; aoqi@0: tty->print_cr(PTR64_FORMAT " %s %c " PTR64_FORMAT " %s %s", aoqi@0: oldptr, wasoop?"oop":" ", oldptr == newptr ? ' ' : '!', aoqi@0: newptr, is_oop?"oop":" ", (wasoop && !is_oop) ? "STALE" : ((wasoop==false&&is_oop==false&&oldptr !=newptr)?"STOMP":" ")); aoqi@0: } aoqi@0: aoqi@0: static void print_me(intptr_t *new_sp, intptr_t *old_sp, bool *was_oops) { aoqi@0: #ifdef _LP64 aoqi@0: tty->print_cr("--------+------address-----+------before-----------+-------after----------+"); aoqi@0: const int incr = 1; // Increment to skip a long, in units of intptr_t aoqi@0: #else aoqi@0: tty->print_cr("--------+--address-+------before-----------+-------after----------+"); aoqi@0: const int incr = 2; // Increment to skip a long, in units of intptr_t aoqi@0: #endif aoqi@0: tty->print_cr("---SP---|"); aoqi@0: for( int i=0; i<16; i++ ) { aoqi@0: tty->print("blob %c%d |"PTR_FORMAT" ","LO"[i>>3],i&7,new_sp); print_ptrs(*old_sp++,*new_sp++,*was_oops++); } aoqi@0: tty->print_cr("--------|"); aoqi@0: for( int i1=0; i1print("argv pad|"PTR_FORMAT" ",new_sp); print_ptrs(*old_sp++,*new_sp++,*was_oops++); } aoqi@0: tty->print(" pad|"PTR_FORMAT" ",new_sp); print_ptrs(*old_sp++,*new_sp++,*was_oops++); aoqi@0: tty->print_cr("--------|"); aoqi@0: tty->print(" G1 |"PTR_FORMAT" ",new_sp); print_longs(*(jlong*)old_sp,*(jlong*)new_sp,was_oops[incr-1]); old_sp += incr; new_sp += incr; was_oops += incr; aoqi@0: tty->print(" G3 |"PTR_FORMAT" ",new_sp); print_longs(*(jlong*)old_sp,*(jlong*)new_sp,was_oops[incr-1]); old_sp += incr; new_sp += incr; was_oops += incr; aoqi@0: tty->print(" G4 |"PTR_FORMAT" ",new_sp); print_longs(*(jlong*)old_sp,*(jlong*)new_sp,was_oops[incr-1]); old_sp += incr; new_sp += incr; was_oops += incr; aoqi@0: tty->print(" G5 |"PTR_FORMAT" ",new_sp); print_longs(*(jlong*)old_sp,*(jlong*)new_sp,was_oops[incr-1]); old_sp += incr; new_sp += incr; was_oops += incr; aoqi@0: tty->print_cr(" FSR |"PTR_FORMAT" "PTR64_FORMAT" "PTR64_FORMAT,new_sp,*(jlong*)old_sp,*(jlong*)new_sp); aoqi@0: old_sp += incr; new_sp += incr; was_oops += incr; aoqi@0: // Skip the floats aoqi@0: tty->print_cr("--Float-|"PTR_FORMAT,new_sp); aoqi@0: tty->print_cr("---FP---|"); aoqi@0: old_sp += incr*32; new_sp += incr*32; was_oops += incr*32; aoqi@0: for( int i2=0; i2<16; i2++ ) { aoqi@0: tty->print("call %c%d |"PTR_FORMAT" ","LI"[i2>>3],i2&7,new_sp); print_ptrs(*old_sp++,*new_sp++,*was_oops++); } aoqi@0: tty->cr(); aoqi@0: } aoqi@0: #endif // SPARC aoqi@0: #endif // PRODUCT aoqi@0: aoqi@0: aoqi@0: void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) { aoqi@0: assert(thread->is_Java_thread(), "polling reference encountered by VM thread"); aoqi@0: assert(thread->thread_state() == _thread_in_Java, "should come from Java code"); aoqi@0: assert(SafepointSynchronize::is_synchronizing(), "polling encountered outside safepoint synchronization"); aoqi@0: aoqi@0: // Uncomment this to get some serious before/after printing of the aoqi@0: // Sparc safepoint-blob frame structure. aoqi@0: /* aoqi@0: intptr_t* sp = thread->last_Java_sp(); aoqi@0: intptr_t stack_copy[150]; aoqi@0: for( int i=0; i<150; i++ ) stack_copy[i] = sp[i]; aoqi@0: bool was_oops[150]; aoqi@0: for( int i=0; i<150; i++ ) aoqi@0: was_oops[i] = stack_copy[i] ? ((oop)stack_copy[i])->is_oop() : false; aoqi@0: */ aoqi@0: aoqi@0: if (ShowSafepointMsgs) { aoqi@0: tty->print("handle_polling_page_exception: "); aoqi@0: } aoqi@0: aoqi@0: if (PrintSafepointStatistics) { aoqi@0: inc_page_trap_count(); aoqi@0: } aoqi@0: aoqi@0: ThreadSafepointState* state = thread->safepoint_state(); aoqi@0: aoqi@0: state->handle_polling_page_exception(); aoqi@0: // print_me(sp,stack_copy,was_oops); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void SafepointSynchronize::print_safepoint_timeout(SafepointTimeoutReason reason) { aoqi@0: if (!timeout_error_printed) { aoqi@0: timeout_error_printed = true; aoqi@0: // Print out the thread infor which didn't reach the safepoint for debugging aoqi@0: // purposes (useful when there are lots of threads in the debugger). aoqi@0: tty->cr(); aoqi@0: tty->print_cr("# SafepointSynchronize::begin: Timeout detected:"); aoqi@0: if (reason == _spinning_timeout) { aoqi@0: tty->print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint."); aoqi@0: } else if (reason == _blocking_timeout) { aoqi@0: tty->print_cr("# SafepointSynchronize::begin: Timed out while waiting for threads to stop."); aoqi@0: } aoqi@0: aoqi@0: tty->print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:"); aoqi@0: ThreadSafepointState *cur_state; aoqi@0: ResourceMark rm; aoqi@0: for(JavaThread *cur_thread = Threads::first(); cur_thread; aoqi@0: cur_thread = cur_thread->next()) { aoqi@0: cur_state = cur_thread->safepoint_state(); aoqi@0: aoqi@0: if (cur_thread->thread_state() != _thread_blocked && aoqi@0: ((reason == _spinning_timeout && cur_state->is_running()) || aoqi@0: (reason == _blocking_timeout && !cur_state->has_called_back()))) { aoqi@0: tty->print("# "); aoqi@0: cur_thread->print(); aoqi@0: tty->cr(); aoqi@0: } aoqi@0: } aoqi@0: tty->print_cr("# SafepointSynchronize::begin: (End of list)"); aoqi@0: } aoqi@0: aoqi@0: // To debug the long safepoint, specify both DieOnSafepointTimeout & aoqi@0: // ShowMessageBoxOnError. aoqi@0: if (DieOnSafepointTimeout) { aoqi@0: char msg[1024]; aoqi@0: VM_Operation *op = VMThread::vm_operation(); aoqi@0: sprintf(msg, "Safepoint sync time longer than " INTX_FORMAT "ms detected when executing %s.", aoqi@0: SafepointTimeoutDelay, aoqi@0: op != NULL ? op->name() : "no vm operation"); aoqi@0: fatal(msg); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // ------------------------------------------------------------------------------------------------------- aoqi@0: // Implementation of ThreadSafepointState aoqi@0: aoqi@0: ThreadSafepointState::ThreadSafepointState(JavaThread *thread) { aoqi@0: _thread = thread; aoqi@0: _type = _running; aoqi@0: _has_called_back = false; aoqi@0: _at_poll_safepoint = false; aoqi@0: } aoqi@0: aoqi@0: void ThreadSafepointState::create(JavaThread *thread) { aoqi@0: ThreadSafepointState *state = new ThreadSafepointState(thread); aoqi@0: thread->set_safepoint_state(state); aoqi@0: } aoqi@0: aoqi@0: void ThreadSafepointState::destroy(JavaThread *thread) { aoqi@0: if (thread->safepoint_state()) { aoqi@0: delete(thread->safepoint_state()); aoqi@0: thread->set_safepoint_state(NULL); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void ThreadSafepointState::examine_state_of_thread() { aoqi@0: assert(is_running(), "better be running or just have hit safepoint poll"); aoqi@0: aoqi@0: JavaThreadState state = _thread->thread_state(); aoqi@0: aoqi@0: // Save the state at the start of safepoint processing. aoqi@0: _orig_thread_state = state; aoqi@0: aoqi@0: // Check for a thread that is suspended. Note that thread resume tries aoqi@0: // to grab the Threads_lock which we own here, so a thread cannot be aoqi@0: // resumed during safepoint synchronization. aoqi@0: aoqi@0: // We check to see if this thread is suspended without locking to aoqi@0: // avoid deadlocking with a third thread that is waiting for this aoqi@0: // thread to be suspended. The third thread can notice the safepoint aoqi@0: // that we're trying to start at the beginning of its SR_lock->wait() aoqi@0: // call. If that happens, then the third thread will block on the aoqi@0: // safepoint while still holding the underlying SR_lock. We won't be aoqi@0: // able to get the SR_lock and we'll deadlock. aoqi@0: // aoqi@0: // We don't need to grab the SR_lock here for two reasons: aoqi@0: // 1) The suspend flags are both volatile and are set with an aoqi@0: // Atomic::cmpxchg() call so we should see the suspended aoqi@0: // state right away. aoqi@0: // 2) We're being called from the safepoint polling loop; if aoqi@0: // we don't see the suspended state on this iteration, then aoqi@0: // we'll come around again. aoqi@0: // aoqi@0: bool is_suspended = _thread->is_ext_suspended(); aoqi@0: if (is_suspended) { aoqi@0: roll_forward(_at_safepoint); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: // Some JavaThread states have an initial safepoint state of aoqi@0: // running, but are actually at a safepoint. We will happily aoqi@0: // agree and update the safepoint state here. aoqi@0: if (SafepointSynchronize::safepoint_safe(_thread, state)) { aoqi@0: SafepointSynchronize::check_for_lazy_critical_native(_thread, state); aoqi@0: roll_forward(_at_safepoint); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: if (state == _thread_in_vm) { aoqi@0: roll_forward(_call_back); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: // All other thread states will continue to run until they aoqi@0: // transition and self-block in state _blocked aoqi@0: // Safepoint polling in compiled code causes the Java threads to do the same. aoqi@0: // Note: new threads may require a malloc so they must be allowed to finish aoqi@0: aoqi@0: assert(is_running(), "examine_state_of_thread on non-running thread"); aoqi@0: return; aoqi@0: } aoqi@0: aoqi@0: // Returns true is thread could not be rolled forward at present position. aoqi@0: void ThreadSafepointState::roll_forward(suspend_type type) { aoqi@0: _type = type; aoqi@0: aoqi@0: switch(_type) { aoqi@0: case _at_safepoint: aoqi@0: SafepointSynchronize::signal_thread_at_safepoint(); aoqi@0: DEBUG_ONLY(_thread->set_visited_for_critical_count(true)); aoqi@0: if (_thread->in_critical()) { aoqi@0: // Notice that this thread is in a critical section aoqi@0: SafepointSynchronize::increment_jni_active_count(); aoqi@0: } aoqi@0: break; aoqi@0: aoqi@0: case _call_back: aoqi@0: set_has_called_back(false); aoqi@0: break; aoqi@0: aoqi@0: case _running: aoqi@0: default: aoqi@0: ShouldNotReachHere(); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void ThreadSafepointState::restart() { aoqi@0: switch(type()) { aoqi@0: case _at_safepoint: aoqi@0: case _call_back: aoqi@0: break; aoqi@0: aoqi@0: case _running: aoqi@0: default: aoqi@0: tty->print_cr("restart thread "INTPTR_FORMAT" with state %d", aoqi@0: _thread, _type); aoqi@0: _thread->print(); aoqi@0: ShouldNotReachHere(); aoqi@0: } aoqi@0: _type = _running; aoqi@0: set_has_called_back(false); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: void ThreadSafepointState::print_on(outputStream *st) const { aoqi@0: const char *s; aoqi@0: aoqi@0: switch(_type) { aoqi@0: case _running : s = "_running"; break; aoqi@0: case _at_safepoint : s = "_at_safepoint"; break; aoqi@0: case _call_back : s = "_call_back"; break; aoqi@0: default: aoqi@0: ShouldNotReachHere(); aoqi@0: } aoqi@0: aoqi@0: st->print_cr("Thread: " INTPTR_FORMAT aoqi@0: " [0x%2x] State: %s _has_called_back %d _at_poll_safepoint %d", aoqi@0: _thread, _thread->osthread()->thread_id(), s, _has_called_back, aoqi@0: _at_poll_safepoint); aoqi@0: aoqi@0: _thread->print_thread_state_on(st); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // --------------------------------------------------------------------------------------------------------------------- aoqi@0: aoqi@0: // Block the thread at the safepoint poll or poll return. aoqi@0: void ThreadSafepointState::handle_polling_page_exception() { aoqi@0: aoqi@0: // Check state. block() will set thread state to thread_in_vm which will aoqi@0: // cause the safepoint state _type to become _call_back. aoqi@0: assert(type() == ThreadSafepointState::_running, aoqi@0: "polling page exception on thread not running state"); aoqi@0: aoqi@0: // Step 1: Find the nmethod from the return address aoqi@0: if (ShowSafepointMsgs && Verbose) { aoqi@0: tty->print_cr("Polling page exception at " INTPTR_FORMAT, thread()->saved_exception_pc()); aoqi@0: } aoqi@0: address real_return_addr = thread()->saved_exception_pc(); aoqi@0: aoqi@0: CodeBlob *cb = CodeCache::find_blob(real_return_addr); aoqi@0: assert(cb != NULL && cb->is_nmethod(), "return address should be in nmethod"); aoqi@0: nmethod* nm = (nmethod*)cb; aoqi@0: aoqi@0: // Find frame of caller aoqi@0: frame stub_fr = thread()->last_frame(); aoqi@0: CodeBlob* stub_cb = stub_fr.cb(); aoqi@0: assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub"); aoqi@0: RegisterMap map(thread(), true); aoqi@0: frame caller_fr = stub_fr.sender(&map); aoqi@0: aoqi@0: // Should only be poll_return or poll aoqi@0: assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" ); aoqi@0: aoqi@0: // This is a poll immediately before a return. The exception handling code aoqi@0: // has already had the effect of causing the return to occur, so the execution aoqi@0: // will continue immediately after the call. In addition, the oopmap at the aoqi@0: // return point does not mark the return value as an oop (if it is), so aoqi@0: // it needs a handle here to be updated. aoqi@0: if( nm->is_at_poll_return(real_return_addr) ) { aoqi@0: // See if return type is an oop. aoqi@0: bool return_oop = nm->method()->is_returning_oop(); aoqi@0: Handle return_value; aoqi@0: if (return_oop) { aoqi@0: // The oop result has been saved on the stack together with all aoqi@0: // the other registers. In order to preserve it over GCs we need aoqi@0: // to keep it in a handle. aoqi@0: oop result = caller_fr.saved_oop_result(&map); aoqi@0: assert(result == NULL || result->is_oop(), "must be oop"); aoqi@0: return_value = Handle(thread(), result); aoqi@0: assert(Universe::heap()->is_in_or_null(result), "must be heap pointer"); aoqi@0: } aoqi@0: aoqi@0: // Block the thread aoqi@0: SafepointSynchronize::block(thread()); aoqi@0: aoqi@0: // restore oop result, if any aoqi@0: if (return_oop) { aoqi@0: caller_fr.set_saved_oop_result(&map, return_value()); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // This is a safepoint poll. Verify the return address and block. aoqi@0: else { aoqi@0: set_at_poll_safepoint(true); aoqi@0: aoqi@0: // verify the blob built the "return address" correctly aoqi@0: assert(real_return_addr == caller_fr.pc(), "must match"); aoqi@0: aoqi@0: // Block the thread aoqi@0: SafepointSynchronize::block(thread()); aoqi@0: set_at_poll_safepoint(false); aoqi@0: aoqi@0: // If we have a pending async exception deoptimize the frame aoqi@0: // as otherwise we may never deliver it. aoqi@0: if (thread()->has_async_condition()) { aoqi@0: ThreadInVMfromJavaNoAsyncException __tiv(thread()); aoqi@0: Deoptimization::deoptimize_frame(thread(), caller_fr.id()); aoqi@0: } aoqi@0: aoqi@0: // If an exception has been installed we must check for a pending deoptimization aoqi@0: // Deoptimize frame if exception has been thrown. aoqi@0: aoqi@0: if (thread()->has_pending_exception() ) { aoqi@0: RegisterMap map(thread(), true); aoqi@0: frame caller_fr = stub_fr.sender(&map); aoqi@0: if (caller_fr.is_deoptimized_frame()) { aoqi@0: // The exception patch will destroy registers that are still aoqi@0: // live and will be needed during deoptimization. Defer the aoqi@0: // Async exception should have defered the exception until the aoqi@0: // next safepoint which will be detected when we get into aoqi@0: // the interpreter so if we have an exception now things aoqi@0: // are messed up. aoqi@0: aoqi@0: fatal("Exception installed and deoptimization is pending"); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: aoqi@0: // aoqi@0: // Statistics & Instrumentations aoqi@0: // aoqi@0: SafepointSynchronize::SafepointStats* SafepointSynchronize::_safepoint_stats = NULL; aoqi@0: jlong SafepointSynchronize::_safepoint_begin_time = 0; aoqi@0: int SafepointSynchronize::_cur_stat_index = 0; aoqi@0: julong SafepointSynchronize::_safepoint_reasons[VM_Operation::VMOp_Terminating]; aoqi@0: julong SafepointSynchronize::_coalesced_vmop_count = 0; aoqi@0: jlong SafepointSynchronize::_max_sync_time = 0; aoqi@0: jlong SafepointSynchronize::_max_vmop_time = 0; aoqi@0: float SafepointSynchronize::_ts_of_current_safepoint = 0.0f; aoqi@0: aoqi@0: static jlong cleanup_end_time = 0; aoqi@0: static bool need_to_track_page_armed_status = false; aoqi@0: static bool init_done = false; aoqi@0: aoqi@0: // Helper method to print the header. aoqi@0: static void print_header() { aoqi@0: tty->print(" vmop " aoqi@0: "[threads: total initially_running wait_to_block] "); aoqi@0: tty->print("[time: spin block sync cleanup vmop] "); aoqi@0: aoqi@0: // no page armed status printed out if it is always armed. aoqi@0: if (need_to_track_page_armed_status) { aoqi@0: tty->print("page_armed "); aoqi@0: } aoqi@0: aoqi@0: tty->print_cr("page_trap_count"); aoqi@0: } aoqi@0: aoqi@0: void SafepointSynchronize::deferred_initialize_stat() { aoqi@0: if (init_done) return; aoqi@0: aoqi@0: if (PrintSafepointStatisticsCount <= 0) { aoqi@0: fatal("Wrong PrintSafepointStatisticsCount"); aoqi@0: } aoqi@0: aoqi@0: // If PrintSafepointStatisticsTimeout is specified, the statistics data will aoqi@0: // be printed right away, in which case, _safepoint_stats will regress to aoqi@0: // a single element array. Otherwise, it is a circular ring buffer with default aoqi@0: // size of PrintSafepointStatisticsCount. aoqi@0: int stats_array_size; aoqi@0: if (PrintSafepointStatisticsTimeout > 0) { aoqi@0: stats_array_size = 1; aoqi@0: PrintSafepointStatistics = true; aoqi@0: } else { aoqi@0: stats_array_size = PrintSafepointStatisticsCount; aoqi@0: } aoqi@0: _safepoint_stats = (SafepointStats*)os::malloc(stats_array_size aoqi@0: * sizeof(SafepointStats), mtInternal); aoqi@0: guarantee(_safepoint_stats != NULL, aoqi@0: "not enough memory for safepoint instrumentation data"); aoqi@0: aoqi@0: if (UseCompilerSafepoints && DeferPollingPageLoopCount >= 0) { aoqi@0: need_to_track_page_armed_status = true; aoqi@0: } aoqi@0: init_done = true; aoqi@0: } aoqi@0: aoqi@0: void SafepointSynchronize::begin_statistics(int nof_threads, int nof_running) { aoqi@0: assert(init_done, "safepoint statistics array hasn't been initialized"); aoqi@0: SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; aoqi@0: aoqi@0: spstat->_time_stamp = _ts_of_current_safepoint; aoqi@0: aoqi@0: VM_Operation *op = VMThread::vm_operation(); aoqi@0: spstat->_vmop_type = (op != NULL ? op->type() : -1); aoqi@0: if (op != NULL) { aoqi@0: _safepoint_reasons[spstat->_vmop_type]++; aoqi@0: } aoqi@0: aoqi@0: spstat->_nof_total_threads = nof_threads; aoqi@0: spstat->_nof_initial_running_threads = nof_running; aoqi@0: spstat->_nof_threads_hit_page_trap = 0; aoqi@0: aoqi@0: // Records the start time of spinning. The real time spent on spinning aoqi@0: // will be adjusted when spin is done. Same trick is applied for time aoqi@0: // spent on waiting for threads to block. aoqi@0: if (nof_running != 0) { aoqi@0: spstat->_time_to_spin = os::javaTimeNanos(); aoqi@0: } else { aoqi@0: spstat->_time_to_spin = 0; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void SafepointSynchronize::update_statistics_on_spin_end() { aoqi@0: SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; aoqi@0: aoqi@0: jlong cur_time = os::javaTimeNanos(); aoqi@0: aoqi@0: spstat->_nof_threads_wait_to_block = _waiting_to_block; aoqi@0: if (spstat->_nof_initial_running_threads != 0) { aoqi@0: spstat->_time_to_spin = cur_time - spstat->_time_to_spin; aoqi@0: } aoqi@0: aoqi@0: if (need_to_track_page_armed_status) { aoqi@0: spstat->_page_armed = (PageArmed == 1); aoqi@0: } aoqi@0: aoqi@0: // Records the start time of waiting for to block. Updated when block is done. aoqi@0: if (_waiting_to_block != 0) { aoqi@0: spstat->_time_to_wait_to_block = cur_time; aoqi@0: } else { aoqi@0: spstat->_time_to_wait_to_block = 0; aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void SafepointSynchronize::update_statistics_on_sync_end(jlong end_time) { aoqi@0: SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; aoqi@0: aoqi@0: if (spstat->_nof_threads_wait_to_block != 0) { aoqi@0: spstat->_time_to_wait_to_block = end_time - aoqi@0: spstat->_time_to_wait_to_block; aoqi@0: } aoqi@0: aoqi@0: // Records the end time of sync which will be used to calculate the total aoqi@0: // vm operation time. Again, the real time spending in syncing will be deducted aoqi@0: // from the start of the sync time later when end_statistics is called. aoqi@0: spstat->_time_to_sync = end_time - _safepoint_begin_time; aoqi@0: if (spstat->_time_to_sync > _max_sync_time) { aoqi@0: _max_sync_time = spstat->_time_to_sync; aoqi@0: } aoqi@0: aoqi@0: spstat->_time_to_do_cleanups = end_time; aoqi@0: } aoqi@0: aoqi@0: void SafepointSynchronize::update_statistics_on_cleanup_end(jlong end_time) { aoqi@0: SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; aoqi@0: aoqi@0: // Record how long spent in cleanup tasks. aoqi@0: spstat->_time_to_do_cleanups = end_time - spstat->_time_to_do_cleanups; aoqi@0: aoqi@0: cleanup_end_time = end_time; aoqi@0: } aoqi@0: aoqi@0: void SafepointSynchronize::end_statistics(jlong vmop_end_time) { aoqi@0: SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; aoqi@0: aoqi@0: // Update the vm operation time. aoqi@0: spstat->_time_to_exec_vmop = vmop_end_time - cleanup_end_time; aoqi@0: if (spstat->_time_to_exec_vmop > _max_vmop_time) { aoqi@0: _max_vmop_time = spstat->_time_to_exec_vmop; aoqi@0: } aoqi@0: // Only the sync time longer than the specified aoqi@0: // PrintSafepointStatisticsTimeout will be printed out right away. aoqi@0: // By default, it is -1 meaning all samples will be put into the list. aoqi@0: if ( PrintSafepointStatisticsTimeout > 0) { aoqi@0: if (spstat->_time_to_sync > PrintSafepointStatisticsTimeout * MICROUNITS) { aoqi@0: print_statistics(); aoqi@0: } aoqi@0: } else { aoqi@0: // The safepoint statistics will be printed out when the _safepoin_stats aoqi@0: // array fills up. aoqi@0: if (_cur_stat_index == PrintSafepointStatisticsCount - 1) { aoqi@0: print_statistics(); aoqi@0: _cur_stat_index = 0; aoqi@0: } else { aoqi@0: _cur_stat_index++; aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void SafepointSynchronize::print_statistics() { aoqi@0: SafepointStats* sstats = _safepoint_stats; aoqi@0: aoqi@0: for (int index = 0; index <= _cur_stat_index; index++) { aoqi@0: if (index % 30 == 0) { aoqi@0: print_header(); aoqi@0: } aoqi@0: sstats = &_safepoint_stats[index]; aoqi@0: tty->print("%.3f: ", sstats->_time_stamp); aoqi@0: tty->print("%-26s [" aoqi@0: INT32_FORMAT_W(8)INT32_FORMAT_W(11)INT32_FORMAT_W(15) aoqi@0: " ] ", aoqi@0: sstats->_vmop_type == -1 ? "no vm operation" : aoqi@0: VM_Operation::name(sstats->_vmop_type), aoqi@0: sstats->_nof_total_threads, aoqi@0: sstats->_nof_initial_running_threads, aoqi@0: sstats->_nof_threads_wait_to_block); aoqi@0: // "/ MICROUNITS " is to convert the unit from nanos to millis. aoqi@0: tty->print(" [" aoqi@0: INT64_FORMAT_W(6)INT64_FORMAT_W(6) aoqi@0: INT64_FORMAT_W(6)INT64_FORMAT_W(6) aoqi@0: INT64_FORMAT_W(6)" ] ", aoqi@0: sstats->_time_to_spin / MICROUNITS, aoqi@0: sstats->_time_to_wait_to_block / MICROUNITS, aoqi@0: sstats->_time_to_sync / MICROUNITS, aoqi@0: sstats->_time_to_do_cleanups / MICROUNITS, aoqi@0: sstats->_time_to_exec_vmop / MICROUNITS); aoqi@0: aoqi@0: if (need_to_track_page_armed_status) { aoqi@0: tty->print(INT32_FORMAT" ", sstats->_page_armed); aoqi@0: } aoqi@0: tty->print_cr(INT32_FORMAT" ", sstats->_nof_threads_hit_page_trap); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: // This method will be called when VM exits. It will first call aoqi@0: // print_statistics to print out the rest of the sampling. Then aoqi@0: // it tries to summarize the sampling. aoqi@0: void SafepointSynchronize::print_stat_on_exit() { aoqi@0: if (_safepoint_stats == NULL) return; aoqi@0: aoqi@0: SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; aoqi@0: aoqi@0: // During VM exit, end_statistics may not get called and in that aoqi@0: // case, if the sync time is less than PrintSafepointStatisticsTimeout, aoqi@0: // don't print it out. aoqi@0: // Approximate the vm op time. aoqi@0: _safepoint_stats[_cur_stat_index]._time_to_exec_vmop = aoqi@0: os::javaTimeNanos() - cleanup_end_time; aoqi@0: aoqi@0: if ( PrintSafepointStatisticsTimeout < 0 || aoqi@0: spstat->_time_to_sync > PrintSafepointStatisticsTimeout * MICROUNITS) { aoqi@0: print_statistics(); aoqi@0: } aoqi@0: tty->cr(); aoqi@0: aoqi@0: // Print out polling page sampling status. aoqi@0: if (!need_to_track_page_armed_status) { aoqi@0: if (UseCompilerSafepoints) { aoqi@0: tty->print_cr("Polling page always armed"); aoqi@0: } aoqi@0: } else { aoqi@0: tty->print_cr("Defer polling page loop count = %d\n", aoqi@0: DeferPollingPageLoopCount); aoqi@0: } aoqi@0: aoqi@0: for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) { aoqi@0: if (_safepoint_reasons[index] != 0) { aoqi@0: tty->print_cr("%-26s"UINT64_FORMAT_W(10), VM_Operation::name(index), aoqi@0: _safepoint_reasons[index]); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: tty->print_cr(UINT64_FORMAT_W(5)" VM operations coalesced during safepoint", aoqi@0: _coalesced_vmop_count); aoqi@0: tty->print_cr("Maximum sync time "INT64_FORMAT_W(5)" ms", aoqi@0: _max_sync_time / MICROUNITS); aoqi@0: tty->print_cr("Maximum vm operation time (except for Exit VM operation) " aoqi@0: INT64_FORMAT_W(5)" ms", aoqi@0: _max_vmop_time / MICROUNITS); aoqi@0: } aoqi@0: aoqi@0: // ------------------------------------------------------------------------------------------------ aoqi@0: // Non-product code aoqi@0: aoqi@0: #ifndef PRODUCT aoqi@0: aoqi@0: void SafepointSynchronize::print_state() { aoqi@0: if (_state == _not_synchronized) { aoqi@0: tty->print_cr("not synchronized"); aoqi@0: } else if (_state == _synchronizing || _state == _synchronized) { aoqi@0: tty->print_cr("State: %s", (_state == _synchronizing) ? "synchronizing" : aoqi@0: "synchronized"); aoqi@0: aoqi@0: for(JavaThread *cur = Threads::first(); cur; cur = cur->next()) { aoqi@0: cur->safepoint_state()->print(); aoqi@0: } aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: void SafepointSynchronize::safepoint_msg(const char* format, ...) { aoqi@0: if (ShowSafepointMsgs) { aoqi@0: va_list ap; aoqi@0: va_start(ap, format); aoqi@0: tty->vprint_cr(format, ap); aoqi@0: va_end(ap); aoqi@0: } aoqi@0: } aoqi@0: aoqi@0: #endif // !PRODUCT