safepoint.cpp revision 6692:4f9fa4b62c18
150477Speter/* 214330Speter * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. 314330Speter * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 414330Speter * 568519Smarcel * This code is free software; you can redistribute it and/or modify it 614330Speter * under the terms of the GNU General Public License version 2 only, as 7155374Srwatson * published by the Free Software Foundation. 814330Speter * 9146806Srwatson * This code is distributed in the hope that it will be useful, but WITHOUT 10146806Srwatson * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11146806Srwatson * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12146806Srwatson * version 2 for more details (a copy is included in the LICENSE file that 13146806Srwatson * accompanied this code). 14156842Snetchild * 1514330Speter * You should have received a copy of the GNU General Public License version 1614330Speter * 2 along with this work; if not, write to the Free Software Foundation, 1714330Speter * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 1814330Speter * 1914330Speter * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 2014330Speter * or visit www.oracle.com if you need additional information or have any 2114330Speter * questions. 2214330Speter * 23160797Sjhb */ 2414330Speter 25160797Sjhb#include "precompiled.hpp" 2614330Speter#include "classfile/stringTable.hpp" 2714330Speter#include "classfile/systemDictionary.hpp" 2814330Speter#include "code/codeCache.hpp" 2914330Speter#include "code/icBuffer.hpp" 30143197Ssobomax#include "code/nmethod.hpp" 3114330Speter#include "code/pcDesc.hpp" 3268583Smarcel#include "code/scopeDesc.hpp" 3314330Speter#include "gc_interface/collectedHeap.hpp" 34143197Ssobomax#include "interpreter/interpreter.hpp" 35143197Ssobomax#include "memory/gcLocker.inline.hpp" 36143197Ssobomax#include "memory/resourceArea.hpp" 3714330Speter#include "memory/universe.inline.hpp" 3814330Speter#include "oops/oop.inline.hpp" 39146806Srwatson#include "oops/symbol.hpp" 40293478Sdchagin#include "runtime/atomic.inline.hpp" 41160798Sjhb#include "runtime/compilationPolicy.hpp" 42160798Sjhb#include "runtime/deoptimization.hpp" 43146806Srwatson#include "runtime/frame.inline.hpp" 44160798Sjhb#include "runtime/interfaceSupport.hpp" 45146806Srwatson#include "runtime/mutexLocker.hpp" 46160798Sjhb#include "runtime/orderAccess.inline.hpp" 47146806Srwatson#include "runtime/osThread.hpp" 48160798Sjhb#include "runtime/safepoint.hpp" 49160798Sjhb#include "runtime/signature.hpp" 50146806Srwatson#include "runtime/stubCodeGenerator.hpp" 51162527Srwatson#include "runtime/stubRoutines.hpp" 52146806Srwatson#include "runtime/sweeper.hpp" 53160798Sjhb#include "runtime/synchronizer.hpp" 54160798Sjhb#include "runtime/thread.inline.hpp" 55160798Sjhb#include "services/memTracker.hpp" 56146806Srwatson#include "services/runtimeService.hpp" 57160798Sjhb#include "utilities/events.hpp" 58160798Sjhb#include "utilities/macros.hpp" 59160798Sjhb#ifdef TARGET_ARCH_x86 60146806Srwatson# include "nativeInst_x86.hpp" 61160798Sjhb# include "vmreg_x86.inline.hpp" 62146806Srwatson#endif 63160798Sjhb#ifdef TARGET_ARCH_sparc 64146806Srwatson# include "nativeInst_sparc.hpp" 65146806Srwatson# include "vmreg_sparc.inline.hpp" 66160798Sjhb#endif 67156842Snetchild#ifdef TARGET_ARCH_zero 68160798Sjhb# include "nativeInst_zero.hpp" 69146806Srwatson# include "vmreg_zero.inline.hpp" 70160798Sjhb#endif 71160798Sjhb#ifdef TARGET_ARCH_arm 72146806Srwatson# include "nativeInst_arm.hpp" 73146806Srwatson# include "vmreg_arm.inline.hpp" 74160798Sjhb#endif 75160798Sjhb#ifdef TARGET_ARCH_ppc 76160798Sjhb# include "nativeInst_ppc.hpp" 77160798Sjhb# include "vmreg_ppc.inline.hpp" 78160798Sjhb#endif 79146806Srwatson#if INCLUDE_ALL_GCS 80160798Sjhb#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp" 81160798Sjhb#include "gc_implementation/shared/suspendibleThreadSet.hpp" 82156842Snetchild#endif // INCLUDE_ALL_GCS 83160798Sjhb#ifdef COMPILER1 84160798Sjhb#include "c1/c1_globals.hpp" 85146806Srwatson#endif 86146806Srwatson 87146806SrwatsonPRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 88227691Sed 89160798Sjhb// -------------------------------------------------------------------------------------------------- 90146806Srwatson// Implementation of Safepoint begin/end 91160798Sjhb 92160798SjhbSafepointSynchronize::SynchronizeState volatile SafepointSynchronize::_state = SafepointSynchronize::_not_synchronized; 93160798Sjhbvolatile int SafepointSynchronize::_waiting_to_block = 0; 94160798Sjhbvolatile int SafepointSynchronize::_safepoint_counter = 0; 95160798Sjhbint SafepointSynchronize::_current_jni_active_count = 0; 96160798Sjhblong SafepointSynchronize::_end_of_last_safepoint = 0; 97234352Sjkimstatic volatile int PageArmed = 0 ; // safepoint polling page is RO|RW vs PROT_NONE 98160798Sjhbstatic volatile int TryingToBlock = 0 ; // proximate value -- for advisory use only 99146806Srwatsonstatic bool timeout_error_printed = false; 100160798Sjhb 101160798Sjhb// Roll all threads forward to a safepoint and suspend them all 102160798Sjhbvoid SafepointSynchronize::begin() { 103160798Sjhb 104219559Savg Thread* myThread = Thread::current(); 105160798Sjhb assert(myThread->is_VM_thread(), "Only VM thread may execute a safepoint"); 106160798Sjhb 107160798Sjhb if (PrintSafepointStatistics || PrintSafepointStatisticsTimeout > 0) { 108160798Sjhb _safepoint_begin_time = os::javaTimeNanos(); 109146806Srwatson _ts_of_current_safepoint = tty->time_stamp().seconds(); 110160798Sjhb } 111146806Srwatson 112160798Sjhb#if INCLUDE_ALL_GCS 113146806Srwatson if (UseConcMarkSweepGC) { 114146806Srwatson // In the future we should investigate whether CMS can use the 115160798Sjhb // more-general mechanism below. DLD (01/05). 116146806Srwatson ConcurrentMarkSweepThread::synchronize(false); 117160798Sjhb } else if (UseG1GC) { 118160798Sjhb SuspendibleThreadSet::synchronize(); 119160798Sjhb } 120160798Sjhb#endif // INCLUDE_ALL_GCS 121146806Srwatson 122161305Snetchild // By getting the Threads_lock, we assure that no threads are about to start or 123161305Snetchild // exit. It is released again in SafepointSynchronize::end(). 124161305Snetchild Threads_lock->lock(); 125161305Snetchild 126160798Sjhb assert( _state == _not_synchronized, "trying to safepoint synchronize with wrong state"); 127146806Srwatson 128146806Srwatson int nof_threads = Threads::number_of_threads(); 129160798Sjhb 130160798Sjhb if (TraceSafepoint) { 131160798Sjhb tty->print_cr("Safepoint synchronization initiated. (%d)", nof_threads); 132146806Srwatson } 133160798Sjhb 134146806Srwatson RuntimeService::record_safepoint_begin(); 135160798Sjhb 136146806Srwatson MutexLocker mu(Safepoint_lock); 137160798Sjhb 138160798Sjhb // Reset the count of active JNI critical threads 139156842Snetchild _current_jni_active_count = 0; 140160798Sjhb 141146806Srwatson // Set number of threads to wait for, before we initiate the callbacks 142160798Sjhb _waiting_to_block = nof_threads; 143146806Srwatson TryingToBlock = 0 ; 144160798Sjhb int still_running = nof_threads; 145146806Srwatson 146160798Sjhb // Save the starting time, so that it can be compared to see if this has taken 147155374Srwatson // too long to complete. 148146806Srwatson jlong safepoint_limit_time; 149160798Sjhb timeout_error_printed = false; 150219559Savg 151146806Srwatson // PrintSafepointStatisticsTimeout can be specified separately. When 152160798Sjhb // specified, PrintSafepointStatistics will be set to true in 153146806Srwatson // deferred_initialize_stat method. The initialization has to be done 154160798Sjhb // early enough to avoid any races. See bug 6880029 for details. 155146806Srwatson if (PrintSafepointStatistics || PrintSafepointStatisticsTimeout > 0) { 156160798Sjhb deferred_initialize_stat(); 157146806Srwatson } 158160798Sjhb 159232799Snetchild // Begin the process of bringing the system to a safepoint. 160238917Sjhb // Java threads can be in several different states and are 161160798Sjhb // stopped by different mechanisms: 162146806Srwatson // 163160798Sjhb // 1. Running interpreted 164160798Sjhb // The interpreter dispatch table is changed to force it to 165160798Sjhb // check for a safepoint condition between bytecodes. 166146806Srwatson // 2. Running in native code 167232799Snetchild // When returning from the native code, a Java thread must check 168162525Srwatson // the safepoint _state to see if we must block. If the 169146806Srwatson // VM thread sees a Java thread in native, it does 170232799Snetchild // not wait for this thread to block. The order of the memory 171160798Sjhb // writes and reads of both the safepoint state and the Java 172160798Sjhb // threads state is critical. In order to guarantee that the 173160798Sjhb // memory writes are serialized with respect to each other, 174146806Srwatson // the VM thread issues a memory barrier instruction 175160798Sjhb // (on MP systems). In order to avoid the overhead of issuing 176160798Sjhb // a memory barrier for each Java thread making native calls, each Java 177160798Sjhb // thread performs a write to a single memory page after changing 178160798Sjhb // the thread state. The VM thread performs a sequence of 179160798Sjhb // mprotect OS calls which forces all previous writes from all 180146806Srwatson // Java threads to be serialized. This is done in the 181162525Srwatson // os::serialize_thread_states() call. This has proven to be 182160798Sjhb // much more efficient than executing a membar instruction 183146806Srwatson // on every call to native code. 184160798Sjhb // 3. Running compiled Code 185146806Srwatson // Compiled code reads a global (Safepoint Polling) page that 186160798Sjhb // is set to fault if we are trying to get to a safepoint. 187146806Srwatson // 4. Blocked 188160798Sjhb // A thread which is blocked will not be allowed to return from the 189146806Srwatson // block condition until the safepoint operation is complete. 190160798Sjhb // 5. In VM or Transitioning between states 191146806Srwatson // If a Java thread is currently running in the VM or transitioning 192160798Sjhb // between states, the safepointing code will wait for the thread to 193146806Srwatson // block itself when it attempts transitions to a new state. 194146806Srwatson // 195160798Sjhb _state = _synchronizing; 196146806Srwatson OrderAccess::fence(); 197160798Sjhb 198146806Srwatson // Flush all thread states to memory 199160798Sjhb if (!UseMembar) { 200146806Srwatson os::serialize_thread_states(); 201160798Sjhb } 202146806Srwatson 203232799Snetchild // Make interpreter safepoint aware 204160798Sjhb Interpreter::notice_safepoints(); 205234359Sjkim 206160798Sjhb if (UseCompilerSafepoints && DeferPollingPageLoopCount < 0) { 207146806Srwatson // Make polling safepoint aware 208160798Sjhb guarantee (PageArmed == 0, "invariant") ; 209160798Sjhb PageArmed = 1 ; 210276810Sdchagin os::make_polling_page_unreadable(); 211293501Sdchagin } 212160798Sjhb 213160798Sjhb // Consider using active_processor_count() ... but that call is expensive. 214160798Sjhb int ncpus = os::processor_count() ; 215146806Srwatson 216146806Srwatson#ifdef ASSERT 217160798Sjhb for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) { 218160798Sjhb assert(cur->safepoint_state()->is_running(), "Illegal initial state"); 219146806Srwatson // Clear the visited flag to ensure that the critical counts are collected properly. 220161305Snetchild cur->set_visited_for_critical_count(false); 221218610Sdchagin } 222184789Sed#endif // ASSERT 223155374Srwatson 224160798Sjhb if (SafepointTimeout) 225146806Srwatson safepoint_limit_time = os::javaTimeNanos() + (jlong)SafepointTimeoutDelay * MICROUNITS; 226160798Sjhb 227146806Srwatson // Iterate through all threads until it have been determined how to stop them all at a safepoint 228160798Sjhb unsigned int iterations = 0; 229166727Sjkim int steps = 0 ; 230146806Srwatson while(still_running > 0) { 231160798Sjhb for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) { 232146806Srwatson assert(!cur->is_ConcurrentGC_thread(), "A concurrent GC thread is unexpectly being suspended"); 233160798Sjhb ThreadSafepointState *cur_state = cur->safepoint_state(); 234160798Sjhb if (cur_state->is_running()) { 235160798Sjhb cur_state->examine_state_of_thread(); 236160798Sjhb if (!cur_state->is_running()) { 237160798Sjhb still_running--; 238160798Sjhb // consider adjusting steps downward: 239160798Sjhb // steps = 0 240160798Sjhb // steps -= NNN 241160798Sjhb // steps >>= 1 242146806Srwatson // steps = MIN(steps, 2000-100) 243160798Sjhb // if (iterations != 0) steps -= NNN 244146806Srwatson } 245160798Sjhb if (TraceSafepoint && Verbose) cur_state->print(); 246160798Sjhb } 247160798Sjhb } 248146806Srwatson 249146806Srwatson if (PrintSafepointStatistics && iterations == 0) { 250162525Srwatson begin_statistics(nof_threads, still_running); 251162525Srwatson } 252232799Snetchild 253160798Sjhb if (still_running > 0) { 254146806Srwatson // Check for if it takes to long 255146806Srwatson if (SafepointTimeout && safepoint_limit_time < os::javaTimeNanos()) { 256146806Srwatson print_safepoint_timeout(_spinning_timeout); 257160798Sjhb } 258160798Sjhb 259146806Srwatson // Spin to avoid context switching. 260160798Sjhb // There's a tension between allowing the mutators to run (and rendezvous) 261146806Srwatson // vs spinning. As the VM thread spins, wasting cycles, it consumes CPU that 262160798Sjhb // a mutator might otherwise use profitably to reach a safepoint. Excessive 263146806Srwatson // spinning by the VM thread on a saturated system can increase rendezvous latency. 264160798Sjhb // Blocking or yielding incur their own penalties in the form of context switching 265160798Sjhb // and the resultant loss of $ residency. 266160798Sjhb // 267146806Srwatson // Further complicating matters is that yield() does not work as naively expected 268160798Sjhb // on many platforms -- yield() does not guarantee that any other ready threads 269160798Sjhb // will run. As such we revert to naked_short_sleep() after some number of iterations. 270160798Sjhb // nakes_short_sleep() is implemented as a short unconditional sleep. 271160798Sjhb // Typical operating systems round a "short" sleep period up to 10 msecs, so sleeping 272293487Sdchagin // can actually increase the time it takes the VM thread to detect that a system-wide 273293487Sdchagin // stop-the-world safepoint has been reached. In a pathological scenario such as that 274293487Sdchagin // described in CR6415670 the VMthread may sleep just before the mutator(s) become safe. 275293487Sdchagin // In that case the mutators will be stalled waiting for the safepoint to complete and the 276162525Srwatson // the VMthread will be sleeping, waiting for the mutators to rendezvous. The VMthread 277162525Srwatson // will eventually wake up and detect that all mutators are safe, at which point 278146806Srwatson // we'll again make progress. 279162525Srwatson // 280162525Srwatson // Beware too that that the VMThread typically runs at elevated priority. 281160798Sjhb // Its default priority is higher than the default mutator priority. 282162525Srwatson // Obviously, this complicates spinning. 283146806Srwatson // 284162525Srwatson // Note too that on Windows XP SwitchThreadTo() has quite different behavior than Sleep(0). 285146806Srwatson // Sleep(0) will _not yield to lower priority threads, while SwitchThreadTo() will. 286293483Sdchagin // 287293483Sdchagin // See the comments in synchronizer.cpp for additional remarks on spinning. 288165410Sjkim // 289165410Sjkim // In the future we might: 290165410Sjkim // 1. Modify the safepoint scheme to avoid potentially unbounded spinning. 291160798Sjhb // This is tricky as the path used by a thread exiting the JVM (say on 292146806Srwatson // on JNI call-out) simply stores into its state field. The burden 293146806Srwatson // is placed on the VM thread, which must poll (spin). 294160798Sjhb // 2. Find something useful to do while spinning. If the safepoint is GC-related 295146806Srwatson // we might aggressively scan the stacks of threads that are already safe. 296160798Sjhb // 3. Use Solaris schedctl to examine the state of the still-running mutators. 297146806Srwatson // If all the mutators are ONPROC there's no reason to sleep or yield. 298160798Sjhb // 4. YieldTo() any still-running mutators that are ready but OFFPROC. 299160798Sjhb // 5. Check system saturation. If the system is not fully saturated then 300219559Savg // simply spin and avoid sleep/yield. 301146806Srwatson // 6. As still-running mutators rendezvous they could unpark the sleeping 302160798Sjhb // VMthread. This works well for still-running mutators that become 303160798Sjhb // safe. The VMthread must still poll for mutators that call-out. 304146806Srwatson // 7. Drive the policy on time-since-begin instead of iterations. 305160798Sjhb // 8. Consider making the spin duration a function of the # of CPUs: 306146806Srwatson // Spin = (((ncpus-1) * M) + K) + F(still_running) 307163734Snetchild // Alternately, instead of counting iterations of the outer loop 308163734Snetchild // we could count the # of threads visited in the inner loop, above. 309160798Sjhb // 9. On windows consider using the return value from SwitchThreadTo() 310146806Srwatson // to drive subsequent spin/SwitchThreadTo()/Sleep(N) decisions. 311160798Sjhb 312146806Srwatson if (UseCompilerSafepoints && int(iterations) == DeferPollingPageLoopCount) { 313146806Srwatson guarantee (PageArmed == 0, "invariant") ; 314160798Sjhb PageArmed = 1 ; 315146806Srwatson os::make_polling_page_unreadable(); 316146806Srwatson } 317160798Sjhb 318158406Snetchild // Instead of (ncpus > 1) consider either (still_running < (ncpus + EPSILON)) or 319165689Snetchild // ((still_running + _waiting_to_block - TryingToBlock)) < ncpus) 320165689Snetchild ++steps ; 321165689Snetchild if (ncpus > 1 && steps < SafepointSpinBeforeYield) { 322165689Snetchild SpinPause() ; // MP-Polite spin 323293505Sdchagin } else 324293505Sdchagin if (steps < DeferThrSuspendLoopCount) { 325160798Sjhb os::naked_yield() ; 326146806Srwatson } else { 327146806Srwatson os::naked_short_sleep(1); 328160798Sjhb } 329146806Srwatson 330160798Sjhb iterations ++ ; 331146806Srwatson } 332160798Sjhb assert(iterations < (uint)max_jint, "We have been iterating in the safepoint loop too long"); 333146806Srwatson } 334160798Sjhb assert(still_running == 0, "sanity check"); 335146806Srwatson 336220028Savg if (PrintSafepointStatistics) { 337220028Savg update_statistics_on_spin_end(); 338220028Savg } 339220028Savg 340160798Sjhb // wait until all threads are stopped 341146806Srwatson while (_waiting_to_block > 0) { 342160798Sjhb if (TraceSafepoint) tty->print_cr("Waiting for %d thread(s) to block", _waiting_to_block); 343155374Srwatson if (!SafepointTimeout || timeout_error_printed) { 344155374Srwatson Safepoint_lock->wait(true); // true, means with no safepoint checks 345160798Sjhb } else { 346232799Snetchild // Compute remaining time 347160798Sjhb jlong remaining_time = safepoint_limit_time - os::javaTimeNanos(); 348146806Srwatson 349160798Sjhb // If there is no remaining time, then there is an error 350146806Srwatson if (remaining_time < 0 || Safepoint_lock->wait(true, remaining_time / MICROUNITS)) { 351146806Srwatson print_safepoint_timeout(_blocking_timeout); 352160798Sjhb } 353146806Srwatson } 354160798Sjhb } 355146806Srwatson assert(_waiting_to_block == 0, "sanity check"); 356234357Sjkim 357234357Sjkim#ifndef PRODUCT 358234357Sjkim if (SafepointTimeout) { 359234357Sjkim jlong current_time = os::javaTimeNanos(); 360234357Sjkim if (safepoint_limit_time < current_time) { 361234357Sjkim tty->print_cr("# SafepointSynchronize: Finished after " 362160798Sjhb INT64_FORMAT_W(6) " ms", 363146806Srwatson ((current_time - safepoint_limit_time) / MICROUNITS + 364160798Sjhb SafepointTimeoutDelay)); 365160798Sjhb } 366160798Sjhb } 367160798Sjhb#endif 368160798Sjhb 369160798Sjhb assert((_safepoint_counter & 0x1) == 0, "must be even"); 370160798Sjhb assert(Threads_lock->owned_by_self(), "must hold Threads_lock"); 371146806Srwatson _safepoint_counter ++; 372160798Sjhb 373146806Srwatson // Record state 374155374Srwatson _state = _synchronized; 375160798Sjhb 376146806Srwatson OrderAccess::fence(); 377160798Sjhb 378146806Srwatson#ifdef ASSERT 379160798Sjhb for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) { 380146806Srwatson // make sure all the threads were visited 381160798Sjhb assert(cur->was_visited_for_critical_count(), "missed a thread"); 382146806Srwatson } 383160798Sjhb#endif // ASSERT 384146806Srwatson 385160798Sjhb // Update the count of active JNI critical regions 386160798Sjhb GC_locker::set_jni_lock_count(_current_jni_active_count); 387160798Sjhb 388160798Sjhb if (TraceSafepoint) { 389160798Sjhb VM_Operation *op = VMThread::vm_operation(); 390146806Srwatson tty->print_cr("Entering safepoint region: %s", (op != NULL) ? op->name() : "no vm operation"); 391160798Sjhb } 392146806Srwatson 393160798Sjhb RuntimeService::record_safepoint_synchronized(); 394146806Srwatson if (PrintSafepointStatistics) { 395162525Srwatson update_statistics_on_sync_end(os::javaTimeNanos()); 396146806Srwatson } 397160798Sjhb 398146806Srwatson // Call stuff that needs to be run when a safepoint is just about to be completed 399146806Srwatson do_cleanup_tasks(); 400146806Srwatson 401160798Sjhb if (PrintSafepointStatistics) { 402146806Srwatson // Record how much time spend on the above cleanup tasks 403160798Sjhb update_statistics_on_cleanup_end(os::javaTimeNanos()); 404160798Sjhb } 405160798Sjhb} 406160798Sjhb 407160798Sjhb// Wake up all threads, so they are ready to resume execution after the safepoint 408160798Sjhb// operation has been carried out 409160798Sjhbvoid SafepointSynchronize::end() { 410160798Sjhb 411160798Sjhb assert(Threads_lock->owned_by_self(), "must hold Threads_lock"); 412160798Sjhb assert((_safepoint_counter & 0x1) == 1, "must be odd"); 413160798Sjhb _safepoint_counter ++; 414160798Sjhb // memory fence isn't required here since an odd _safepoint_counter 415160798Sjhb // value can do no harm and a fence is issued below anyway. 416155374Srwatson 417218101Sdchagin DEBUG_ONLY(Thread* myThread = Thread::current();) 418218101Sdchagin assert(myThread->is_VM_thread(), "Only VM thread can execute a safepoint"); 419177257Srdivacky 420177257Srdivacky if (PrintSafepointStatistics) { 421171998Skib end_statistics(os::javaTimeNanos()); 422171998Skib } 423161305Snetchild 424161305Snetchild#ifdef ASSERT 425163760Snetchild // A pending_exception cannot be installed during a safepoint. The threads 426163760Snetchild // may install an async exception after they come back from a safepoint into 427163760Snetchild // pending_exception after they unblock. But that should happen later. 428163760Snetchild for(JavaThread *cur = Threads::first(); cur; cur = cur->next()) { 429163760Snetchild assert (!(cur->has_pending_exception() && 430228957Sjhb cur->safepoint_state()->is_at_poll_safepoint()), 431228957Sjhb "safepoint installed a pending exception"); 432146806Srwatson } 433161305Snetchild#endif // ASSERT 434160798Sjhb 435293546Sdchagin if (PageArmed) { 436293546Sdchagin // Make polling safepoint aware 437293546Sdchagin os::make_polling_page_readable(); 438293546Sdchagin PageArmed = 0 ; 439293546Sdchagin } 440160798Sjhb 441161305Snetchild // Remove safepoint check from interpreter 442161305Snetchild Interpreter::ignore_safepoints(); 443161305Snetchild 444272020Sbz { 445161305Snetchild MutexLocker mu(Safepoint_lock); 446161305Snetchild 447161305Snetchild assert(_state == _synchronized, "must be synchronized before ending safepoint synchronization"); 448161305Snetchild 449161305Snetchild // Set to not synchronized, so the threads will not go into the signal_thread_blocked method 450161305Snetchild // when they get restarted. 451161305Snetchild _state = _not_synchronized; 452161305Snetchild OrderAccess::fence(); 453161305Snetchild 454172220Sdwmalone if (TraceSafepoint) { 455162525Srwatson tty->print_cr("Leaving safepoint region"); 456161305Snetchild } 457165689Snetchild 458165689Snetchild // Start suspended threads 459228957Sjhb for(JavaThread *current = Threads::first(); current; current = current->next()) { 460228957Sjhb // A problem occurring on Solaris is when attempting to restart threads 461228957Sjhb // the first #cpus - 1 go well, but then the VMThread is preempted when we get 462232799Snetchild // to the next one (since it has been running the longest). We then have 463160798Sjhb // to wait for a cpu to become available before we can continue restarting 464160798Sjhb // threads. 465160798Sjhb // FIXME: This causes the performance of the VM to degrade when active and with 466232799Snetchild // large numbers of threads. Apparently this is due to the synchronous nature 467161305Snetchild // of suspending threads. 468161305Snetchild // 469161305Snetchild // TODO-FIXME: the comments above are vestigial and no longer apply. 470161305Snetchild // Furthermore, using solaris' schedctl in this particular context confers no benefit 471161305Snetchild if (VMThreadHintNoPreempt) { 472161305Snetchild os::hint_no_preempt(); 473161305Snetchild } 474161305Snetchild ThreadSafepointState* cur_state = current->safepoint_state(); 475161305Snetchild assert(cur_state->type() != ThreadSafepointState::_running, "Thread not suspended at safepoint"); 476161305Snetchild cur_state->restart(); 477161305Snetchild assert(cur_state->is_running(), "safepoint state has not been reset"); 478161305Snetchild } 479160798Sjhb 480293503Sdchagin RuntimeService::record_safepoint_end(); 481293503Sdchagin 482293503Sdchagin // Release threads lock, so threads can be created/destroyed again. It will also starts all threads 483159799Snetchild // blocked in signal_thread_blocked 484232799Snetchild Threads_lock->unlock(); 485160798Sjhb 486160798Sjhb } 487160798Sjhb#if INCLUDE_ALL_GCS 488232799Snetchild // If there are any concurrent GC threads resume them. 489160798Sjhb if (UseConcMarkSweepGC) { 490160798Sjhb ConcurrentMarkSweepThread::desynchronize(false); 491160798Sjhb } else if (UseG1GC) { 492160798Sjhb SuspendibleThreadSet::desynchronize(); 493160798Sjhb } 494232799Snetchild#endif // INCLUDE_ALL_GCS 495160798Sjhb // record this time so VMThread can keep track how much time has elapsed 496177997Skib // since last safepoint. 497168014Sjulian _end_of_last_safepoint = os::javaTimeMillis(); 498177997Skib} 499177997Skib 500177997Skibbool SafepointSynchronize::is_cleanup_needed() { 501177997Skib // Need a safepoint if some inline cache buffers is non-empty 502177997Skib if (!InlineCacheBuffer::is_empty()) return true; 503177997Skib return false; 504177997Skib} 505177997Skib 506177997Skib 507177997Skib 508177997Skib// Various cleaning tasks that should be done periodically at safepoints 509177997Skibvoid SafepointSynchronize::do_cleanup_tasks() { 510177997Skib { 511177997Skib TraceTime t1("deflating idle monitors", TraceSafepointCleanupTime); 512177997Skib ObjectSynchronizer::deflate_idle_monitors(); 513227693Sed } 514177997Skib 515177997Skib { 516177997Skib TraceTime t2("updating inline caches", TraceSafepointCleanupTime); 517177997Skib InlineCacheBuffer::update_inline_caches(); 518177997Skib } 519177997Skib { 520293533Sdchagin TraceTime t3("compilation policy safepoint handler", TraceSafepointCleanupTime); 521293533Sdchagin CompilationPolicy::policy()->do_safepoint_work(); 522293512Sdchagin } 523293512Sdchagin 524293512Sdchagin { 525293555Sdchagin TraceTime t4("mark nmethods", TraceSafepointCleanupTime); 526293555Sdchagin NMethodSweeper::mark_active_nmethods(); 527160798Sjhb } 528232799Snetchild 529178976Srdivacky if (SymbolTable::needs_rehashing()) { 530178976Srdivacky TraceTime t5("rehashing symbol table", TraceSafepointCleanupTime); 531293897Sglebius SymbolTable::rehash_table(); 532293897Sglebius } 533178257Sjkim 534178257Sjkim if (StringTable::needs_rehashing()) { 535178257Sjkim TraceTime t6("rehashing string table", TraceSafepointCleanupTime); 536178257Sjkim StringTable::rehash_table(); 537232799Snetchild } 538232799Snetchild 539232799Snetchild // rotate log files? 540232799Snetchild if (UseGCLogFileRotation) { 541293546Sdchagin gclog_or_tty->rotate_log(false); 542293585Sdchagin } 543232799Snetchild 544293582Sdchagin { 545293582Sdchagin // CMS delays purging the CLDG until the beginning of the next safepoint and to 546232799Snetchild // make sure concurrent sweep is done 547232799Snetchild TraceTime t7("purging class loader data graph", TraceSafepointCleanupTime); 548293549Sdchagin ClassLoaderDataGraph::purge_if_needed(); 549232799Snetchild } 550293567Sdchagin 551293567Sdchagin if (MemTracker::is_on()) { 552232799Snetchild MemTracker::sync(); 553232799Snetchild } 554232799Snetchild} 555232799Snetchild 556232799Snetchild 557293549Sdchaginbool SafepointSynchronize::safepoint_safe(JavaThread *thread, JavaThreadState state) { 558293546Sdchagin switch(state) { 559293508Sdchagin case _thread_in_native: 560293508Sdchagin // native threads are safe if they have no java stack or have walkable stack 561234352Sjkim return !thread->has_last_Java_frame() || thread->frame_anchor()->walkable(); 562232799Snetchild 563232799Snetchild // blocked threads should have already have walkable stack 564232799Snetchild case _thread_blocked: 565232799Snetchild assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "blocked and not walkable"); 566232799Snetchild return true; 567232799Snetchild 568232799Snetchild default: 569232799Snetchild return false; 570293588Sdchagin } 571293588Sdchagin} 572293588Sdchagin 573232799Snetchild 574232799Snetchild// See if the thread is running inside a lazy critical native and 575232799Snetchild// update the thread critical count if so. Also set a suspend flag to 576293510Sdchagin// cause the native wrapper to return into the JVM to do the unlock 577293510Sdchagin// once the native finishes. 578293510Sdchaginvoid SafepointSynchronize::check_for_lazy_critical_native(JavaThread *thread, JavaThreadState state) { 579293510Sdchagin if (state == _thread_in_native && 580232799Snetchild thread->has_last_Java_frame() && 581232799Snetchild thread->frame_anchor()->walkable()) { 582232799Snetchild // This thread might be in a critical native nmethod so look at 583232799Snetchild // the top of the stack and increment the critical count if it 584293592Sdchagin // is. 585293588Sdchagin frame wrapper_frame = thread->last_frame(); 586293588Sdchagin CodeBlob* stub_cb = wrapper_frame.cb(); 587293588Sdchagin if (stub_cb != NULL && 588232799Snetchild stub_cb->is_nmethod() && 589232799Snetchild stub_cb->as_nmethod_or_null()->is_lazy_critical_native()) { 590232799Snetchild // A thread could potentially be in a critical native across 591293569Sdchagin // more than one safepoint, so only update the critical state on 592293569Sdchagin // the first one. When it returns it will perform the unlock. 593 if (!thread->do_critical_native_unlock()) { 594#ifdef ASSERT 595 if (!thread->in_critical()) { 596 GC_locker::increment_debug_jni_lock_count(); 597 } 598#endif 599 thread->enter_critical(); 600 // Make sure the native wrapper calls back on return to 601 // perform the needed critical unlock. 602 thread->set_critical_native_unlock(); 603 } 604 } 605 } 606} 607 608 609 610// ------------------------------------------------------------------------------------------------------- 611// Implementation of Safepoint callback point 612 613void SafepointSynchronize::block(JavaThread *thread) { 614 assert(thread != NULL, "thread must be set"); 615 assert(thread->is_Java_thread(), "not a Java thread"); 616 617 // Threads shouldn't block if they are in the middle of printing, but... 618 ttyLocker::break_tty_lock_for_safepoint(os::current_thread_id()); 619 620 // Only bail from the block() call if the thread is gone from the 621 // thread list; starting to exit should still block. 622 if (thread->is_terminated()) { 623 // block current thread if we come here from native code when VM is gone 624 thread->block_if_vm_exited(); 625 626 // otherwise do nothing 627 return; 628 } 629 630 JavaThreadState state = thread->thread_state(); 631 thread->frame_anchor()->make_walkable(thread); 632 633 // Check that we have a valid thread_state at this point 634 switch(state) { 635 case _thread_in_vm_trans: 636 case _thread_in_Java: // From compiled code 637 638 // We are highly likely to block on the Safepoint_lock. In order to avoid blocking in this case, 639 // we pretend we are still in the VM. 640 thread->set_thread_state(_thread_in_vm); 641 642 if (is_synchronizing()) { 643 Atomic::inc (&TryingToBlock) ; 644 } 645 646 // We will always be holding the Safepoint_lock when we are examine the state 647 // of a thread. Hence, the instructions between the Safepoint_lock->lock() and 648 // Safepoint_lock->unlock() are happening atomic with regards to the safepoint code 649 Safepoint_lock->lock_without_safepoint_check(); 650 if (is_synchronizing()) { 651 // Decrement the number of threads to wait for and signal vm thread 652 assert(_waiting_to_block > 0, "sanity check"); 653 _waiting_to_block--; 654 thread->safepoint_state()->set_has_called_back(true); 655 656 DEBUG_ONLY(thread->set_visited_for_critical_count(true)); 657 if (thread->in_critical()) { 658 // Notice that this thread is in a critical section 659 increment_jni_active_count(); 660 } 661 662 // Consider (_waiting_to_block < 2) to pipeline the wakeup of the VM thread 663 if (_waiting_to_block == 0) { 664 Safepoint_lock->notify_all(); 665 } 666 } 667 668 // We transition the thread to state _thread_blocked here, but 669 // we can't do our usual check for external suspension and then 670 // self-suspend after the lock_without_safepoint_check() call 671 // below because we are often called during transitions while 672 // we hold different locks. That would leave us suspended while 673 // holding a resource which results in deadlocks. 674 thread->set_thread_state(_thread_blocked); 675 Safepoint_lock->unlock(); 676 677 // We now try to acquire the threads lock. Since this lock is hold by the VM thread during 678 // the entire safepoint, the threads will all line up here during the safepoint. 679 Threads_lock->lock_without_safepoint_check(); 680 // restore original state. This is important if the thread comes from compiled code, so it 681 // will continue to execute with the _thread_in_Java state. 682 thread->set_thread_state(state); 683 Threads_lock->unlock(); 684 break; 685 686 case _thread_in_native_trans: 687 case _thread_blocked_trans: 688 case _thread_new_trans: 689 if (thread->safepoint_state()->type() == ThreadSafepointState::_call_back) { 690 thread->print_thread_state(); 691 fatal("Deadlock in safepoint code. " 692 "Should have called back to the VM before blocking."); 693 } 694 695 // We transition the thread to state _thread_blocked here, but 696 // we can't do our usual check for external suspension and then 697 // self-suspend after the lock_without_safepoint_check() call 698 // below because we are often called during transitions while 699 // we hold different locks. That would leave us suspended while 700 // holding a resource which results in deadlocks. 701 thread->set_thread_state(_thread_blocked); 702 703 // It is not safe to suspend a thread if we discover it is in _thread_in_native_trans. Hence, 704 // the safepoint code might still be waiting for it to block. We need to change the state here, 705 // so it can see that it is at a safepoint. 706 707 // Block until the safepoint operation is completed. 708 Threads_lock->lock_without_safepoint_check(); 709 710 // Restore state 711 thread->set_thread_state(state); 712 713 Threads_lock->unlock(); 714 break; 715 716 default: 717 fatal(err_msg("Illegal threadstate encountered: %d", state)); 718 } 719 720 // Check for pending. async. exceptions or suspends - except if the 721 // thread was blocked inside the VM. has_special_runtime_exit_condition() 722 // is called last since it grabs a lock and we only want to do that when 723 // we must. 724 // 725 // Note: we never deliver an async exception at a polling point as the 726 // compiler may not have an exception handler for it. The polling 727 // code will notice the async and deoptimize and the exception will 728 // be delivered. (Polling at a return point is ok though). Sure is 729 // a lot of bother for a deprecated feature... 730 // 731 // We don't deliver an async exception if the thread state is 732 // _thread_in_native_trans so JNI functions won't be called with 733 // a surprising pending exception. If the thread state is going back to java, 734 // async exception is checked in check_special_condition_for_native_trans(). 735 736 if (state != _thread_blocked_trans && 737 state != _thread_in_vm_trans && 738 thread->has_special_runtime_exit_condition()) { 739 thread->handle_special_runtime_exit_condition( 740 !thread->is_at_poll_safepoint() && (state != _thread_in_native_trans)); 741 } 742} 743 744// ------------------------------------------------------------------------------------------------------ 745// Exception handlers 746 747 748void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) { 749 assert(thread->is_Java_thread(), "polling reference encountered by VM thread"); 750 assert(thread->thread_state() == _thread_in_Java, "should come from Java code"); 751 assert(SafepointSynchronize::is_synchronizing(), "polling encountered outside safepoint synchronization"); 752 753 if (ShowSafepointMsgs) { 754 tty->print("handle_polling_page_exception: "); 755 } 756 757 if (PrintSafepointStatistics) { 758 inc_page_trap_count(); 759 } 760 761 ThreadSafepointState* state = thread->safepoint_state(); 762 763 state->handle_polling_page_exception(); 764} 765 766 767void SafepointSynchronize::print_safepoint_timeout(SafepointTimeoutReason reason) { 768 if (!timeout_error_printed) { 769 timeout_error_printed = true; 770 // Print out the thread info which didn't reach the safepoint for debugging 771 // purposes (useful when there are lots of threads in the debugger). 772 tty->cr(); 773 tty->print_cr("# SafepointSynchronize::begin: Timeout detected:"); 774 if (reason == _spinning_timeout) { 775 tty->print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint."); 776 } else if (reason == _blocking_timeout) { 777 tty->print_cr("# SafepointSynchronize::begin: Timed out while waiting for threads to stop."); 778 } 779 780 tty->print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:"); 781 ThreadSafepointState *cur_state; 782 ResourceMark rm; 783 for(JavaThread *cur_thread = Threads::first(); cur_thread; 784 cur_thread = cur_thread->next()) { 785 cur_state = cur_thread->safepoint_state(); 786 787 if (cur_thread->thread_state() != _thread_blocked && 788 ((reason == _spinning_timeout && cur_state->is_running()) || 789 (reason == _blocking_timeout && !cur_state->has_called_back()))) { 790 tty->print("# "); 791 cur_thread->print(); 792 tty->cr(); 793 } 794 } 795 tty->print_cr("# SafepointSynchronize::begin: (End of list)"); 796 } 797 798 // To debug the long safepoint, specify both DieOnSafepointTimeout & 799 // ShowMessageBoxOnError. 800 if (DieOnSafepointTimeout) { 801 char msg[1024]; 802 VM_Operation *op = VMThread::vm_operation(); 803 sprintf(msg, "Safepoint sync time longer than " INTX_FORMAT "ms detected when executing %s.", 804 SafepointTimeoutDelay, 805 op != NULL ? op->name() : "no vm operation"); 806 fatal(msg); 807 } 808} 809 810 811// ------------------------------------------------------------------------------------------------------- 812// Implementation of ThreadSafepointState 813 814ThreadSafepointState::ThreadSafepointState(JavaThread *thread) { 815 _thread = thread; 816 _type = _running; 817 _has_called_back = false; 818 _at_poll_safepoint = false; 819} 820 821void ThreadSafepointState::create(JavaThread *thread) { 822 ThreadSafepointState *state = new ThreadSafepointState(thread); 823 thread->set_safepoint_state(state); 824} 825 826void ThreadSafepointState::destroy(JavaThread *thread) { 827 if (thread->safepoint_state()) { 828 delete(thread->safepoint_state()); 829 thread->set_safepoint_state(NULL); 830 } 831} 832 833void ThreadSafepointState::examine_state_of_thread() { 834 assert(is_running(), "better be running or just have hit safepoint poll"); 835 836 JavaThreadState state = _thread->thread_state(); 837 838 // Save the state at the start of safepoint processing. 839 _orig_thread_state = state; 840 841 // Check for a thread that is suspended. Note that thread resume tries 842 // to grab the Threads_lock which we own here, so a thread cannot be 843 // resumed during safepoint synchronization. 844 845 // We check to see if this thread is suspended without locking to 846 // avoid deadlocking with a third thread that is waiting for this 847 // thread to be suspended. The third thread can notice the safepoint 848 // that we're trying to start at the beginning of its SR_lock->wait() 849 // call. If that happens, then the third thread will block on the 850 // safepoint while still holding the underlying SR_lock. We won't be 851 // able to get the SR_lock and we'll deadlock. 852 // 853 // We don't need to grab the SR_lock here for two reasons: 854 // 1) The suspend flags are both volatile and are set with an 855 // Atomic::cmpxchg() call so we should see the suspended 856 // state right away. 857 // 2) We're being called from the safepoint polling loop; if 858 // we don't see the suspended state on this iteration, then 859 // we'll come around again. 860 // 861 bool is_suspended = _thread->is_ext_suspended(); 862 if (is_suspended) { 863 roll_forward(_at_safepoint); 864 return; 865 } 866 867 // Some JavaThread states have an initial safepoint state of 868 // running, but are actually at a safepoint. We will happily 869 // agree and update the safepoint state here. 870 if (SafepointSynchronize::safepoint_safe(_thread, state)) { 871 SafepointSynchronize::check_for_lazy_critical_native(_thread, state); 872 roll_forward(_at_safepoint); 873 return; 874 } 875 876 if (state == _thread_in_vm) { 877 roll_forward(_call_back); 878 return; 879 } 880 881 // All other thread states will continue to run until they 882 // transition and self-block in state _blocked 883 // Safepoint polling in compiled code causes the Java threads to do the same. 884 // Note: new threads may require a malloc so they must be allowed to finish 885 886 assert(is_running(), "examine_state_of_thread on non-running thread"); 887 return; 888} 889 890// Returns true is thread could not be rolled forward at present position. 891void ThreadSafepointState::roll_forward(suspend_type type) { 892 _type = type; 893 894 switch(_type) { 895 case _at_safepoint: 896 SafepointSynchronize::signal_thread_at_safepoint(); 897 DEBUG_ONLY(_thread->set_visited_for_critical_count(true)); 898 if (_thread->in_critical()) { 899 // Notice that this thread is in a critical section 900 SafepointSynchronize::increment_jni_active_count(); 901 } 902 break; 903 904 case _call_back: 905 set_has_called_back(false); 906 break; 907 908 case _running: 909 default: 910 ShouldNotReachHere(); 911 } 912} 913 914void ThreadSafepointState::restart() { 915 switch(type()) { 916 case _at_safepoint: 917 case _call_back: 918 break; 919 920 case _running: 921 default: 922 tty->print_cr("restart thread "INTPTR_FORMAT" with state %d", 923 _thread, _type); 924 _thread->print(); 925 ShouldNotReachHere(); 926 } 927 _type = _running; 928 set_has_called_back(false); 929} 930 931 932void ThreadSafepointState::print_on(outputStream *st) const { 933 const char *s; 934 935 switch(_type) { 936 case _running : s = "_running"; break; 937 case _at_safepoint : s = "_at_safepoint"; break; 938 case _call_back : s = "_call_back"; break; 939 default: 940 ShouldNotReachHere(); 941 } 942 943 st->print_cr("Thread: " INTPTR_FORMAT 944 " [0x%2x] State: %s _has_called_back %d _at_poll_safepoint %d", 945 _thread, _thread->osthread()->thread_id(), s, _has_called_back, 946 _at_poll_safepoint); 947 948 _thread->print_thread_state_on(st); 949} 950 951 952// --------------------------------------------------------------------------------------------------------------------- 953 954// Block the thread at the safepoint poll or poll return. 955void ThreadSafepointState::handle_polling_page_exception() { 956 957 // Check state. block() will set thread state to thread_in_vm which will 958 // cause the safepoint state _type to become _call_back. 959 assert(type() == ThreadSafepointState::_running, 960 "polling page exception on thread not running state"); 961 962 // Step 1: Find the nmethod from the return address 963 if (ShowSafepointMsgs && Verbose) { 964 tty->print_cr("Polling page exception at " INTPTR_FORMAT, thread()->saved_exception_pc()); 965 } 966 address real_return_addr = thread()->saved_exception_pc(); 967 968 CodeBlob *cb = CodeCache::find_blob(real_return_addr); 969 assert(cb != NULL && cb->is_nmethod(), "return address should be in nmethod"); 970 nmethod* nm = (nmethod*)cb; 971 972 // Find frame of caller 973 frame stub_fr = thread()->last_frame(); 974 CodeBlob* stub_cb = stub_fr.cb(); 975 assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub"); 976 RegisterMap map(thread(), true); 977 frame caller_fr = stub_fr.sender(&map); 978 979 // Should only be poll_return or poll 980 assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" ); 981 982 // This is a poll immediately before a return. The exception handling code 983 // has already had the effect of causing the return to occur, so the execution 984 // will continue immediately after the call. In addition, the oopmap at the 985 // return point does not mark the return value as an oop (if it is), so 986 // it needs a handle here to be updated. 987 if( nm->is_at_poll_return(real_return_addr) ) { 988 // See if return type is an oop. 989 bool return_oop = nm->method()->is_returning_oop(); 990 Handle return_value; 991 if (return_oop) { 992 // The oop result has been saved on the stack together with all 993 // the other registers. In order to preserve it over GCs we need 994 // to keep it in a handle. 995 oop result = caller_fr.saved_oop_result(&map); 996 assert(result == NULL || result->is_oop(), "must be oop"); 997 return_value = Handle(thread(), result); 998 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer"); 999 } 1000 1001 // Block the thread 1002 SafepointSynchronize::block(thread()); 1003 1004 // restore oop result, if any 1005 if (return_oop) { 1006 caller_fr.set_saved_oop_result(&map, return_value()); 1007 } 1008 } 1009 1010 // This is a safepoint poll. Verify the return address and block. 1011 else { 1012 set_at_poll_safepoint(true); 1013 1014 // verify the blob built the "return address" correctly 1015 assert(real_return_addr == caller_fr.pc(), "must match"); 1016 1017 // Block the thread 1018 SafepointSynchronize::block(thread()); 1019 set_at_poll_safepoint(false); 1020 1021 // If we have a pending async exception deoptimize the frame 1022 // as otherwise we may never deliver it. 1023 if (thread()->has_async_condition()) { 1024 ThreadInVMfromJavaNoAsyncException __tiv(thread()); 1025 Deoptimization::deoptimize_frame(thread(), caller_fr.id()); 1026 } 1027 1028 // If an exception has been installed we must check for a pending deoptimization 1029 // Deoptimize frame if exception has been thrown. 1030 1031 if (thread()->has_pending_exception() ) { 1032 RegisterMap map(thread(), true); 1033 frame caller_fr = stub_fr.sender(&map); 1034 if (caller_fr.is_deoptimized_frame()) { 1035 // The exception patch will destroy registers that are still 1036 // live and will be needed during deoptimization. Defer the 1037 // Async exception should have deferred the exception until the 1038 // next safepoint which will be detected when we get into 1039 // the interpreter so if we have an exception now things 1040 // are messed up. 1041 1042 fatal("Exception installed and deoptimization is pending"); 1043 } 1044 } 1045 } 1046} 1047 1048 1049// 1050// Statistics & Instrumentations 1051// 1052SafepointSynchronize::SafepointStats* SafepointSynchronize::_safepoint_stats = NULL; 1053jlong SafepointSynchronize::_safepoint_begin_time = 0; 1054int SafepointSynchronize::_cur_stat_index = 0; 1055julong SafepointSynchronize::_safepoint_reasons[VM_Operation::VMOp_Terminating]; 1056julong SafepointSynchronize::_coalesced_vmop_count = 0; 1057jlong SafepointSynchronize::_max_sync_time = 0; 1058jlong SafepointSynchronize::_max_vmop_time = 0; 1059float SafepointSynchronize::_ts_of_current_safepoint = 0.0f; 1060 1061static jlong cleanup_end_time = 0; 1062static bool need_to_track_page_armed_status = false; 1063static bool init_done = false; 1064 1065// Helper method to print the header. 1066static void print_header() { 1067 tty->print(" vmop " 1068 "[threads: total initially_running wait_to_block] "); 1069 tty->print("[time: spin block sync cleanup vmop] "); 1070 1071 // no page armed status printed out if it is always armed. 1072 if (need_to_track_page_armed_status) { 1073 tty->print("page_armed "); 1074 } 1075 1076 tty->print_cr("page_trap_count"); 1077} 1078 1079void SafepointSynchronize::deferred_initialize_stat() { 1080 if (init_done) return; 1081 1082 if (PrintSafepointStatisticsCount <= 0) { 1083 fatal("Wrong PrintSafepointStatisticsCount"); 1084 } 1085 1086 // If PrintSafepointStatisticsTimeout is specified, the statistics data will 1087 // be printed right away, in which case, _safepoint_stats will regress to 1088 // a single element array. Otherwise, it is a circular ring buffer with default 1089 // size of PrintSafepointStatisticsCount. 1090 int stats_array_size; 1091 if (PrintSafepointStatisticsTimeout > 0) { 1092 stats_array_size = 1; 1093 PrintSafepointStatistics = true; 1094 } else { 1095 stats_array_size = PrintSafepointStatisticsCount; 1096 } 1097 _safepoint_stats = (SafepointStats*)os::malloc(stats_array_size 1098 * sizeof(SafepointStats), mtInternal); 1099 guarantee(_safepoint_stats != NULL, 1100 "not enough memory for safepoint instrumentation data"); 1101 1102 if (UseCompilerSafepoints && DeferPollingPageLoopCount >= 0) { 1103 need_to_track_page_armed_status = true; 1104 } 1105 init_done = true; 1106} 1107 1108void SafepointSynchronize::begin_statistics(int nof_threads, int nof_running) { 1109 assert(init_done, "safepoint statistics array hasn't been initialized"); 1110 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; 1111 1112 spstat->_time_stamp = _ts_of_current_safepoint; 1113 1114 VM_Operation *op = VMThread::vm_operation(); 1115 spstat->_vmop_type = (op != NULL ? op->type() : -1); 1116 if (op != NULL) { 1117 _safepoint_reasons[spstat->_vmop_type]++; 1118 } 1119 1120 spstat->_nof_total_threads = nof_threads; 1121 spstat->_nof_initial_running_threads = nof_running; 1122 spstat->_nof_threads_hit_page_trap = 0; 1123 1124 // Records the start time of spinning. The real time spent on spinning 1125 // will be adjusted when spin is done. Same trick is applied for time 1126 // spent on waiting for threads to block. 1127 if (nof_running != 0) { 1128 spstat->_time_to_spin = os::javaTimeNanos(); 1129 } else { 1130 spstat->_time_to_spin = 0; 1131 } 1132} 1133 1134void SafepointSynchronize::update_statistics_on_spin_end() { 1135 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; 1136 1137 jlong cur_time = os::javaTimeNanos(); 1138 1139 spstat->_nof_threads_wait_to_block = _waiting_to_block; 1140 if (spstat->_nof_initial_running_threads != 0) { 1141 spstat->_time_to_spin = cur_time - spstat->_time_to_spin; 1142 } 1143 1144 if (need_to_track_page_armed_status) { 1145 spstat->_page_armed = (PageArmed == 1); 1146 } 1147 1148 // Records the start time of waiting for to block. Updated when block is done. 1149 if (_waiting_to_block != 0) { 1150 spstat->_time_to_wait_to_block = cur_time; 1151 } else { 1152 spstat->_time_to_wait_to_block = 0; 1153 } 1154} 1155 1156void SafepointSynchronize::update_statistics_on_sync_end(jlong end_time) { 1157 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; 1158 1159 if (spstat->_nof_threads_wait_to_block != 0) { 1160 spstat->_time_to_wait_to_block = end_time - 1161 spstat->_time_to_wait_to_block; 1162 } 1163 1164 // Records the end time of sync which will be used to calculate the total 1165 // vm operation time. Again, the real time spending in syncing will be deducted 1166 // from the start of the sync time later when end_statistics is called. 1167 spstat->_time_to_sync = end_time - _safepoint_begin_time; 1168 if (spstat->_time_to_sync > _max_sync_time) { 1169 _max_sync_time = spstat->_time_to_sync; 1170 } 1171 1172 spstat->_time_to_do_cleanups = end_time; 1173} 1174 1175void SafepointSynchronize::update_statistics_on_cleanup_end(jlong end_time) { 1176 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; 1177 1178 // Record how long spent in cleanup tasks. 1179 spstat->_time_to_do_cleanups = end_time - spstat->_time_to_do_cleanups; 1180 1181 cleanup_end_time = end_time; 1182} 1183 1184void SafepointSynchronize::end_statistics(jlong vmop_end_time) { 1185 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; 1186 1187 // Update the vm operation time. 1188 spstat->_time_to_exec_vmop = vmop_end_time - cleanup_end_time; 1189 if (spstat->_time_to_exec_vmop > _max_vmop_time) { 1190 _max_vmop_time = spstat->_time_to_exec_vmop; 1191 } 1192 // Only the sync time longer than the specified 1193 // PrintSafepointStatisticsTimeout will be printed out right away. 1194 // By default, it is -1 meaning all samples will be put into the list. 1195 if ( PrintSafepointStatisticsTimeout > 0) { 1196 if (spstat->_time_to_sync > PrintSafepointStatisticsTimeout * MICROUNITS) { 1197 print_statistics(); 1198 } 1199 } else { 1200 // The safepoint statistics will be printed out when the _safepoin_stats 1201 // array fills up. 1202 if (_cur_stat_index == PrintSafepointStatisticsCount - 1) { 1203 print_statistics(); 1204 _cur_stat_index = 0; 1205 } else { 1206 _cur_stat_index++; 1207 } 1208 } 1209} 1210 1211void SafepointSynchronize::print_statistics() { 1212 SafepointStats* sstats = _safepoint_stats; 1213 1214 for (int index = 0; index <= _cur_stat_index; index++) { 1215 if (index % 30 == 0) { 1216 print_header(); 1217 } 1218 sstats = &_safepoint_stats[index]; 1219 tty->print("%.3f: ", sstats->_time_stamp); 1220 tty->print("%-26s [" 1221 INT32_FORMAT_W(8)INT32_FORMAT_W(11)INT32_FORMAT_W(15) 1222 " ] ", 1223 sstats->_vmop_type == -1 ? "no vm operation" : 1224 VM_Operation::name(sstats->_vmop_type), 1225 sstats->_nof_total_threads, 1226 sstats->_nof_initial_running_threads, 1227 sstats->_nof_threads_wait_to_block); 1228 // "/ MICROUNITS " is to convert the unit from nanos to millis. 1229 tty->print(" [" 1230 INT64_FORMAT_W(6)INT64_FORMAT_W(6) 1231 INT64_FORMAT_W(6)INT64_FORMAT_W(6) 1232 INT64_FORMAT_W(6)" ] ", 1233 sstats->_time_to_spin / MICROUNITS, 1234 sstats->_time_to_wait_to_block / MICROUNITS, 1235 sstats->_time_to_sync / MICROUNITS, 1236 sstats->_time_to_do_cleanups / MICROUNITS, 1237 sstats->_time_to_exec_vmop / MICROUNITS); 1238 1239 if (need_to_track_page_armed_status) { 1240 tty->print(INT32_FORMAT" ", sstats->_page_armed); 1241 } 1242 tty->print_cr(INT32_FORMAT" ", sstats->_nof_threads_hit_page_trap); 1243 } 1244} 1245 1246// This method will be called when VM exits. It will first call 1247// print_statistics to print out the rest of the sampling. Then 1248// it tries to summarize the sampling. 1249void SafepointSynchronize::print_stat_on_exit() { 1250 if (_safepoint_stats == NULL) return; 1251 1252 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index]; 1253 1254 // During VM exit, end_statistics may not get called and in that 1255 // case, if the sync time is less than PrintSafepointStatisticsTimeout, 1256 // don't print it out. 1257 // Approximate the vm op time. 1258 _safepoint_stats[_cur_stat_index]._time_to_exec_vmop = 1259 os::javaTimeNanos() - cleanup_end_time; 1260 1261 if ( PrintSafepointStatisticsTimeout < 0 || 1262 spstat->_time_to_sync > PrintSafepointStatisticsTimeout * MICROUNITS) { 1263 print_statistics(); 1264 } 1265 tty->cr(); 1266 1267 // Print out polling page sampling status. 1268 if (!need_to_track_page_armed_status) { 1269 if (UseCompilerSafepoints) { 1270 tty->print_cr("Polling page always armed"); 1271 } 1272 } else { 1273 tty->print_cr("Defer polling page loop count = %d\n", 1274 DeferPollingPageLoopCount); 1275 } 1276 1277 for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) { 1278 if (_safepoint_reasons[index] != 0) { 1279 tty->print_cr("%-26s"UINT64_FORMAT_W(10), VM_Operation::name(index), 1280 _safepoint_reasons[index]); 1281 } 1282 } 1283 1284 tty->print_cr(UINT64_FORMAT_W(5)" VM operations coalesced during safepoint", 1285 _coalesced_vmop_count); 1286 tty->print_cr("Maximum sync time "INT64_FORMAT_W(5)" ms", 1287 _max_sync_time / MICROUNITS); 1288 tty->print_cr("Maximum vm operation time (except for Exit VM operation) " 1289 INT64_FORMAT_W(5)" ms", 1290 _max_vmop_time / MICROUNITS); 1291} 1292 1293// ------------------------------------------------------------------------------------------------ 1294// Non-product code 1295 1296#ifndef PRODUCT 1297 1298void SafepointSynchronize::print_state() { 1299 if (_state == _not_synchronized) { 1300 tty->print_cr("not synchronized"); 1301 } else if (_state == _synchronizing || _state == _synchronized) { 1302 tty->print_cr("State: %s", (_state == _synchronizing) ? "synchronizing" : 1303 "synchronized"); 1304 1305 for(JavaThread *cur = Threads::first(); cur; cur = cur->next()) { 1306 cur->safepoint_state()->print(); 1307 } 1308 } 1309} 1310 1311void SafepointSynchronize::safepoint_msg(const char* format, ...) { 1312 if (ShowSafepointMsgs) { 1313 va_list ap; 1314 va_start(ap, format); 1315 tty->vprint_cr(format, ap); 1316 va_end(ap); 1317 } 1318} 1319 1320#endif // !PRODUCT 1321