< prev index next >

src/hotspot/share/runtime/safepoint.cpp

Print this page
rev 47413 : Introduce SafepointMechanism
rev 47415 : Add Thread Local handshakes and thread local polling


  34 #include "gc/shared/collectedHeap.hpp"
  35 #include "gc/shared/gcLocker.inline.hpp"
  36 #include "gc/shared/strongRootsScope.hpp"
  37 #include "gc/shared/workgroup.hpp"
  38 #include "interpreter/interpreter.hpp"
  39 #include "logging/log.hpp"
  40 #include "logging/logStream.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "memory/universe.inline.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "oops/symbol.hpp"
  45 #include "runtime/atomic.hpp"
  46 #include "runtime/compilationPolicy.hpp"
  47 #include "runtime/deoptimization.hpp"
  48 #include "runtime/frame.inline.hpp"
  49 #include "runtime/interfaceSupport.hpp"
  50 #include "runtime/mutexLocker.hpp"
  51 #include "runtime/orderAccess.inline.hpp"
  52 #include "runtime/osThread.hpp"
  53 #include "runtime/safepoint.hpp"

  54 #include "runtime/signature.hpp"
  55 #include "runtime/stubCodeGenerator.hpp"
  56 #include "runtime/stubRoutines.hpp"
  57 #include "runtime/sweeper.hpp"
  58 #include "runtime/synchronizer.hpp"
  59 #include "runtime/thread.inline.hpp"
  60 #include "runtime/timerTrace.hpp"
  61 #include "services/runtimeService.hpp"
  62 #include "trace/tracing.hpp"
  63 #include "trace/traceMacros.hpp"
  64 #include "utilities/events.hpp"
  65 #include "utilities/macros.hpp"
  66 #if INCLUDE_ALL_GCS
  67 #include "gc/cms/concurrentMarkSweepThread.hpp"
  68 #include "gc/g1/suspendibleThreadSet.hpp"
  69 #endif // INCLUDE_ALL_GCS
  70 #ifdef COMPILER1
  71 #include "c1/c1_globals.hpp"
  72 #endif
  73 


 163   //     Java threads to be serialized.  This is done in the
 164   //     os::serialize_thread_states() call.  This has proven to be
 165   //     much more efficient than executing a membar instruction
 166   //     on every call to native code.
 167   //  3. Running compiled Code
 168   //     Compiled code reads a global (Safepoint Polling) page that
 169   //     is set to fault if we are trying to get to a safepoint.
 170   //  4. Blocked
 171   //     A thread which is blocked will not be allowed to return from the
 172   //     block condition until the safepoint operation is complete.
 173   //  5. In VM or Transitioning between states
 174   //     If a Java thread is currently running in the VM or transitioning
 175   //     between states, the safepointing code will wait for the thread to
 176   //     block itself when it attempts transitions to a new state.
 177   //
 178   {
 179     EventSafepointStateSynchronization sync_event;
 180     int initial_running = 0;
 181 
 182     _state            = _synchronizing;
 183     OrderAccess::fence();









 184 
 185     // Flush all thread states to memory
 186     if (!UseMembar) {
 187       os::serialize_thread_states();
 188     }
 189 

 190     // Make interpreter safepoint aware
 191     Interpreter::notice_safepoints();
 192 
 193     if (DeferPollingPageLoopCount < 0) {
 194       // Make polling safepoint aware
 195       guarantee (PageArmed == 0, "invariant") ;
 196       PageArmed = 1 ;
 197       os::make_polling_page_unreadable();
 198     }

 199 
 200     // Consider using active_processor_count() ... but that call is expensive.
 201     int ncpus = os::processor_count() ;
 202 
 203 #ifdef ASSERT
 204     for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) {
 205       assert(cur->safepoint_state()->is_running(), "Illegal initial state");
 206       // Clear the visited flag to ensure that the critical counts are collected properly.
 207       cur->set_visited_for_critical_count(false);
 208     }
 209 #endif // ASSERT
 210 
 211     if (SafepointTimeout)
 212       safepoint_limit_time = os::javaTimeNanos() + (jlong)SafepointTimeoutDelay * MICROUNITS;
 213 
 214     // Iterate through all threads until it have been determined how to stop them all at a safepoint
 215     unsigned int iterations = 0;
 216     int steps = 0 ;
 217     while(still_running > 0) {
 218       for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) {


 287         //    on JNI call-out) simply stores into its state field.  The burden
 288         //    is placed on the VM thread, which must poll (spin).
 289         // 2. Find something useful to do while spinning.  If the safepoint is GC-related
 290         //    we might aggressively scan the stacks of threads that are already safe.
 291         // 3. Use Solaris schedctl to examine the state of the still-running mutators.
 292         //    If all the mutators are ONPROC there's no reason to sleep or yield.
 293         // 4. YieldTo() any still-running mutators that are ready but OFFPROC.
 294         // 5. Check system saturation.  If the system is not fully saturated then
 295         //    simply spin and avoid sleep/yield.
 296         // 6. As still-running mutators rendezvous they could unpark the sleeping
 297         //    VMthread.  This works well for still-running mutators that become
 298         //    safe.  The VMthread must still poll for mutators that call-out.
 299         // 7. Drive the policy on time-since-begin instead of iterations.
 300         // 8. Consider making the spin duration a function of the # of CPUs:
 301         //    Spin = (((ncpus-1) * M) + K) + F(still_running)
 302         //    Alternately, instead of counting iterations of the outer loop
 303         //    we could count the # of threads visited in the inner loop, above.
 304         // 9. On windows consider using the return value from SwitchThreadTo()
 305         //    to drive subsequent spin/SwitchThreadTo()/Sleep(N) decisions.
 306 
 307         if (int(iterations) == DeferPollingPageLoopCount) {
 308           guarantee (PageArmed == 0, "invariant") ;
 309           PageArmed = 1 ;
 310           os::make_polling_page_unreadable();
 311         }
 312 
 313         // Instead of (ncpus > 1) consider either (still_running < (ncpus + EPSILON)) or
 314         // ((still_running + _waiting_to_block - TryingToBlock)) < ncpus)
 315         ++steps ;
 316         if (ncpus > 1 && steps < SafepointSpinBeforeYield) {
 317           SpinPause() ;     // MP-Polite spin
 318         } else
 319           if (steps < DeferThrSuspendLoopCount) {
 320             os::naked_yield() ;
 321           } else {
 322             os::naked_short_sleep(1);
 323           }
 324 
 325         iterations ++ ;
 326       }
 327       assert(iterations < (uint)max_jint, "We have been iterating in the safepoint loop too long");


 437   EventSafepointEnd event;
 438   int safepoint_id = safepoint_counter(); // Keep the odd counter as "id"
 439 
 440   assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
 441   assert((_safepoint_counter & 0x1) == 1, "must be odd");
 442   _safepoint_counter ++;
 443   // memory fence isn't required here since an odd _safepoint_counter
 444   // value can do no harm and a fence is issued below anyway.
 445 
 446   DEBUG_ONLY(Thread* myThread = Thread::current();)
 447   assert(myThread->is_VM_thread(), "Only VM thread can execute a safepoint");
 448 
 449   if (PrintSafepointStatistics) {
 450     end_statistics(os::javaTimeNanos());
 451   }
 452 
 453 #ifdef ASSERT
 454   // A pending_exception cannot be installed during a safepoint.  The threads
 455   // may install an async exception after they come back from a safepoint into
 456   // pending_exception after they unblock.  But that should happen later.
 457   for(JavaThread *cur = Threads::first(); cur; cur = cur->next()) {
 458     assert (!(cur->has_pending_exception() &&
 459               cur->safepoint_state()->is_at_poll_safepoint()),
 460             "safepoint installed a pending exception");
 461   }
 462 #endif // ASSERT
 463 
 464   if (PageArmed) {

 465     // Make polling safepoint aware
 466     os::make_polling_page_readable();
 467     PageArmed = 0 ;
 468   }
 469 

 470   // Remove safepoint check from interpreter
 471   Interpreter::ignore_safepoints();

 472 
 473   {
 474     MutexLocker mu(Safepoint_lock);
 475 
 476     assert(_state == _synchronized, "must be synchronized before ending safepoint synchronization");
 477 










 478     // Set to not synchronized, so the threads will not go into the signal_thread_blocked method
 479     // when they get restarted.
 480     _state = _not_synchronized;
 481     OrderAccess::fence();
 482 
 483     log_debug(safepoint)("Leaving safepoint region");
 484 
 485     // Start suspended threads
 486     for(JavaThread *current = Threads::first(); current; current = current->next()) {
 487       // A problem occurring on Solaris is when attempting to restart threads
 488       // the first #cpus - 1 go well, but then the VMThread is preempted when we get
 489       // to the next one (since it has been running the longest).  We then have
 490       // to wait for a cpu to become available before we can continue restarting
 491       // threads.
 492       // FIXME: This causes the performance of the VM to degrade when active and with
 493       // large numbers of threads.  Apparently this is due to the synchronous nature
 494       // of suspending threads.
 495       //
 496       // TODO-FIXME: the comments above are vestigial and no longer apply.
 497       // Furthermore, using solaris' schedctl in this particular context confers no benefit
 498       if (VMThreadHintNoPreempt) {
 499         os::hint_no_preempt();
 500       }
 501       ThreadSafepointState* cur_state = current->safepoint_state();
 502       assert(cur_state->type() != ThreadSafepointState::_running, "Thread not suspended at safepoint");
 503       cur_state->restart();
 504       assert(cur_state->is_running(), "safepoint state has not been reset");
 505     }

 506 
 507     RuntimeService::record_safepoint_end();
 508 
 509     // Release threads lock, so threads can be created/destroyed again. It will also starts all threads
 510     // blocked in signal_thread_blocked
 511     Threads_lock->unlock();
 512 
 513   }
 514 #if INCLUDE_ALL_GCS
 515   // If there are any concurrent GC threads resume them.
 516   if (UseConcMarkSweepGC) {
 517     ConcurrentMarkSweepThread::desynchronize(false);
 518   } else if (UseG1GC) {
 519     SuspendibleThreadSet::desynchronize();
 520   }
 521 #endif // INCLUDE_ALL_GCS
 522   // record this time so VMThread can keep track how much time has elapsed
 523   // since last safepoint.
 524   _end_of_last_safepoint = os::javaTimeMillis();
 525 


 847   // We don't deliver an async exception if the thread state is
 848   // _thread_in_native_trans so JNI functions won't be called with
 849   // a surprising pending exception. If the thread state is going back to java,
 850   // async exception is checked in check_special_condition_for_native_trans().
 851 
 852   if (state != _thread_blocked_trans &&
 853       state != _thread_in_vm_trans &&
 854       thread->has_special_runtime_exit_condition()) {
 855     thread->handle_special_runtime_exit_condition(
 856       !thread->is_at_poll_safepoint() && (state != _thread_in_native_trans));
 857   }
 858 }
 859 
 860 // ------------------------------------------------------------------------------------------------------
 861 // Exception handlers
 862 
 863 
 864 void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
 865   assert(thread->is_Java_thread(), "polling reference encountered by VM thread");
 866   assert(thread->thread_state() == _thread_in_Java, "should come from Java code");

 867   assert(SafepointSynchronize::is_synchronizing(), "polling encountered outside safepoint synchronization");

 868 
 869   if (ShowSafepointMsgs) {
 870     tty->print("handle_polling_page_exception: ");
 871   }
 872 
 873   if (PrintSafepointStatistics) {
 874     inc_page_trap_count();
 875   }
 876 
 877   ThreadSafepointState* state = thread->safepoint_state();
 878 
 879   state->handle_polling_page_exception();
 880 }
 881 
 882 
 883 void SafepointSynchronize::print_safepoint_timeout(SafepointTimeoutReason reason) {
 884   if (!timeout_error_printed) {
 885     timeout_error_printed = true;
 886     // Print out the thread info which didn't reach the safepoint for debugging
 887     // purposes (useful when there are lots of threads in the debugger).
 888     tty->cr();
 889     tty->print_cr("# SafepointSynchronize::begin: Timeout detected:");
 890     if (reason ==  _spinning_timeout) {
 891       tty->print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint.");
 892     } else if (reason == _blocking_timeout) {
 893       tty->print_cr("# SafepointSynchronize::begin: Timed out while waiting for threads to stop.");
 894     }
 895 
 896     tty->print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:");
 897     ThreadSafepointState *cur_state;
 898     ResourceMark rm;
 899     for(JavaThread *cur_thread = Threads::first(); cur_thread;
 900         cur_thread = cur_thread->next()) {
 901       cur_state = cur_thread->safepoint_state();
 902 
 903       if (cur_thread->thread_state() != _thread_blocked &&
 904           ((reason == _spinning_timeout && cur_state->is_running()) ||
 905            (reason == _blocking_timeout && !cur_state->has_called_back()))) {
 906         tty->print("# ");
 907         cur_thread->print();
 908         tty->cr();
 909       }
 910     }
 911     tty->print_cr("# SafepointSynchronize::begin: (End of list)");
 912   }
 913 
 914   // To debug the long safepoint, specify both DieOnSafepointTimeout &
 915   // ShowMessageBoxOnError.
 916   if (DieOnSafepointTimeout) {
 917     fatal("Safepoint sync time longer than " INTX_FORMAT "ms detected when executing %s.",
 918           SafepointTimeoutDelay, VMThread::vm_safepoint_description());
 919   }


1045   const char *s = NULL;
1046 
1047   switch(_type) {
1048     case _running                : s = "_running";              break;
1049     case _at_safepoint           : s = "_at_safepoint";         break;
1050     case _call_back              : s = "_call_back";            break;
1051     default:
1052       ShouldNotReachHere();
1053   }
1054 
1055   st->print_cr("Thread: " INTPTR_FORMAT
1056               "  [0x%2x] State: %s _has_called_back %d _at_poll_safepoint %d",
1057                p2i(_thread), _thread->osthread()->thread_id(), s, _has_called_back,
1058                _at_poll_safepoint);
1059 
1060   _thread->print_thread_state_on(st);
1061 }
1062 
1063 // ---------------------------------------------------------------------------------------------------------------------
1064 
1065 // Block the thread at the safepoint poll or poll return.
1066 void ThreadSafepointState::handle_polling_page_exception() {
1067 
1068   // Check state.  block() will set thread state to thread_in_vm which will
1069   // cause the safepoint state _type to become _call_back.
1070   assert(type() == ThreadSafepointState::_running,
1071          "polling page exception on thread not running state");

1072 
1073   // Step 1: Find the nmethod from the return address
1074   if (ShowSafepointMsgs && Verbose) {
1075     tty->print_cr("Polling page exception at " INTPTR_FORMAT, p2i(thread()->saved_exception_pc()));
1076   }
1077   address real_return_addr = thread()->saved_exception_pc();
1078 
1079   CodeBlob *cb = CodeCache::find_blob(real_return_addr);
1080   assert(cb != NULL && cb->is_compiled(), "return address should be in nmethod");
1081   CompiledMethod* nm = (CompiledMethod*)cb;
1082 
1083   // Find frame of caller
1084   frame stub_fr = thread()->last_frame();
1085   CodeBlob* stub_cb = stub_fr.cb();
1086   assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub");
1087   RegisterMap map(thread(), true);
1088   frame caller_fr = stub_fr.sender(&map);
1089 
1090   // Should only be poll_return or poll
1091   assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" );


1093   // This is a poll immediately before a return. The exception handling code
1094   // has already had the effect of causing the return to occur, so the execution
1095   // will continue immediately after the call. In addition, the oopmap at the
1096   // return point does not mark the return value as an oop (if it is), so
1097   // it needs a handle here to be updated.
1098   if( nm->is_at_poll_return(real_return_addr) ) {
1099     // See if return type is an oop.
1100     bool return_oop = nm->method()->is_returning_oop();
1101     Handle return_value;
1102     if (return_oop) {
1103       // The oop result has been saved on the stack together with all
1104       // the other registers. In order to preserve it over GCs we need
1105       // to keep it in a handle.
1106       oop result = caller_fr.saved_oop_result(&map);
1107       assert(oopDesc::is_oop_or_null(result), "must be oop");
1108       return_value = Handle(thread(), result);
1109       assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
1110     }
1111 
1112     // Block the thread
1113     SafepointSynchronize::block(thread());
1114 
1115     // restore oop result, if any
1116     if (return_oop) {
1117       caller_fr.set_saved_oop_result(&map, return_value());
1118     }
1119   }
1120 
1121   // This is a safepoint poll. Verify the return address and block.
1122   else {
1123     set_at_poll_safepoint(true);
1124 
1125     // verify the blob built the "return address" correctly
1126     assert(real_return_addr == caller_fr.pc(), "must match");
1127 
1128     // Block the thread
1129     SafepointSynchronize::block(thread());
1130     set_at_poll_safepoint(false);
1131 
1132     // If we have a pending async exception deoptimize the frame
1133     // as otherwise we may never deliver it.
1134     if (thread()->has_async_condition()) {
1135       ThreadInVMfromJavaNoAsyncException __tiv(thread());
1136       Deoptimization::deoptimize_frame(thread(), caller_fr.id());
1137     }
1138 
1139     // If an exception has been installed we must check for a pending deoptimization
1140     // Deoptimize frame if exception has been thrown.
1141 
1142     if (thread()->has_pending_exception() ) {
1143       RegisterMap map(thread(), true);
1144       frame caller_fr = stub_fr.sender(&map);
1145       if (caller_fr.is_deoptimized_frame()) {
1146         // The exception patch will destroy registers that are still
1147         // live and will be needed during deoptimization. Defer the
1148         // Async exception should have deferred the exception until the
1149         // next safepoint which will be detected when we get into


1390                 _coalesced_vmop_count);
1391   tty->print_cr("Maximum sync time  " INT64_FORMAT_W(5) " ms",
1392                 (int64_t)(_max_sync_time / MICROUNITS));
1393   tty->print_cr("Maximum vm operation time (except for Exit VM operation)  "
1394                 INT64_FORMAT_W(5) " ms",
1395                 (int64_t)(_max_vmop_time / MICROUNITS));
1396 }
1397 
1398 // ------------------------------------------------------------------------------------------------
1399 // Non-product code
1400 
1401 #ifndef PRODUCT
1402 
1403 void SafepointSynchronize::print_state() {
1404   if (_state == _not_synchronized) {
1405     tty->print_cr("not synchronized");
1406   } else if (_state == _synchronizing || _state == _synchronized) {
1407     tty->print_cr("State: %s", (_state == _synchronizing) ? "synchronizing" :
1408                   "synchronized");
1409 
1410     for(JavaThread *cur = Threads::first(); cur; cur = cur->next()) {
1411        cur->safepoint_state()->print();
1412     }
1413   }
1414 }
1415 
1416 void SafepointSynchronize::safepoint_msg(const char* format, ...) {
1417   if (ShowSafepointMsgs) {
1418     va_list ap;
1419     va_start(ap, format);
1420     tty->vprint_cr(format, ap);
1421     va_end(ap);
1422   }
1423 }
1424 
1425 #endif // !PRODUCT


  34 #include "gc/shared/collectedHeap.hpp"
  35 #include "gc/shared/gcLocker.inline.hpp"
  36 #include "gc/shared/strongRootsScope.hpp"
  37 #include "gc/shared/workgroup.hpp"
  38 #include "interpreter/interpreter.hpp"
  39 #include "logging/log.hpp"
  40 #include "logging/logStream.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "memory/universe.inline.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "oops/symbol.hpp"
  45 #include "runtime/atomic.hpp"
  46 #include "runtime/compilationPolicy.hpp"
  47 #include "runtime/deoptimization.hpp"
  48 #include "runtime/frame.inline.hpp"
  49 #include "runtime/interfaceSupport.hpp"
  50 #include "runtime/mutexLocker.hpp"
  51 #include "runtime/orderAccess.inline.hpp"
  52 #include "runtime/osThread.hpp"
  53 #include "runtime/safepoint.hpp"
  54 #include "runtime/safepointMechanism.inline.hpp"
  55 #include "runtime/signature.hpp"
  56 #include "runtime/stubCodeGenerator.hpp"
  57 #include "runtime/stubRoutines.hpp"
  58 #include "runtime/sweeper.hpp"
  59 #include "runtime/synchronizer.hpp"
  60 #include "runtime/thread.inline.hpp"
  61 #include "runtime/timerTrace.hpp"
  62 #include "services/runtimeService.hpp"
  63 #include "trace/tracing.hpp"
  64 #include "trace/traceMacros.hpp"
  65 #include "utilities/events.hpp"
  66 #include "utilities/macros.hpp"
  67 #if INCLUDE_ALL_GCS
  68 #include "gc/cms/concurrentMarkSweepThread.hpp"
  69 #include "gc/g1/suspendibleThreadSet.hpp"
  70 #endif // INCLUDE_ALL_GCS
  71 #ifdef COMPILER1
  72 #include "c1/c1_globals.hpp"
  73 #endif
  74 


 164   //     Java threads to be serialized.  This is done in the
 165   //     os::serialize_thread_states() call.  This has proven to be
 166   //     much more efficient than executing a membar instruction
 167   //     on every call to native code.
 168   //  3. Running compiled Code
 169   //     Compiled code reads a global (Safepoint Polling) page that
 170   //     is set to fault if we are trying to get to a safepoint.
 171   //  4. Blocked
 172   //     A thread which is blocked will not be allowed to return from the
 173   //     block condition until the safepoint operation is complete.
 174   //  5. In VM or Transitioning between states
 175   //     If a Java thread is currently running in the VM or transitioning
 176   //     between states, the safepointing code will wait for the thread to
 177   //     block itself when it attempts transitions to a new state.
 178   //
 179   {
 180     EventSafepointStateSynchronization sync_event;
 181     int initial_running = 0;
 182 
 183     _state            = _synchronizing;
 184 
 185     if (SafepointMechanism::uses_thread_local_poll()) {
 186       // Arming the per thread poll while having _state != _not_synchronized means safepointing
 187       log_trace(safepoint)("Setting thread local yield flag for threads");
 188       for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) {
 189         // Make sure the threads start polling, it is time to yield.
 190         SafepointMechanism::arm_local_poll(cur); // release store, global state -> local state
 191       }
 192     }
 193     OrderAccess::fence(); // storestore|storeload, global state -> local state
 194 
 195     // Flush all thread states to memory
 196     if (!UseMembar) {
 197       os::serialize_thread_states();
 198     }
 199 
 200     if (SafepointMechanism::uses_global_page_poll()) {
 201       // Make interpreter safepoint aware
 202       Interpreter::notice_safepoints();
 203 
 204       if (DeferPollingPageLoopCount < 0) {
 205         // Make polling safepoint aware
 206         guarantee (PageArmed == 0, "invariant") ;
 207         PageArmed = 1 ;
 208         os::make_polling_page_unreadable();
 209       }
 210     }
 211 
 212     // Consider using active_processor_count() ... but that call is expensive.
 213     int ncpus = os::processor_count() ;
 214 
 215 #ifdef ASSERT
 216     for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) {
 217       assert(cur->safepoint_state()->is_running(), "Illegal initial state");
 218       // Clear the visited flag to ensure that the critical counts are collected properly.
 219       cur->set_visited_for_critical_count(false);
 220     }
 221 #endif // ASSERT
 222 
 223     if (SafepointTimeout)
 224       safepoint_limit_time = os::javaTimeNanos() + (jlong)SafepointTimeoutDelay * MICROUNITS;
 225 
 226     // Iterate through all threads until it have been determined how to stop them all at a safepoint
 227     unsigned int iterations = 0;
 228     int steps = 0 ;
 229     while(still_running > 0) {
 230       for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) {


 299         //    on JNI call-out) simply stores into its state field.  The burden
 300         //    is placed on the VM thread, which must poll (spin).
 301         // 2. Find something useful to do while spinning.  If the safepoint is GC-related
 302         //    we might aggressively scan the stacks of threads that are already safe.
 303         // 3. Use Solaris schedctl to examine the state of the still-running mutators.
 304         //    If all the mutators are ONPROC there's no reason to sleep or yield.
 305         // 4. YieldTo() any still-running mutators that are ready but OFFPROC.
 306         // 5. Check system saturation.  If the system is not fully saturated then
 307         //    simply spin and avoid sleep/yield.
 308         // 6. As still-running mutators rendezvous they could unpark the sleeping
 309         //    VMthread.  This works well for still-running mutators that become
 310         //    safe.  The VMthread must still poll for mutators that call-out.
 311         // 7. Drive the policy on time-since-begin instead of iterations.
 312         // 8. Consider making the spin duration a function of the # of CPUs:
 313         //    Spin = (((ncpus-1) * M) + K) + F(still_running)
 314         //    Alternately, instead of counting iterations of the outer loop
 315         //    we could count the # of threads visited in the inner loop, above.
 316         // 9. On windows consider using the return value from SwitchThreadTo()
 317         //    to drive subsequent spin/SwitchThreadTo()/Sleep(N) decisions.
 318 
 319         if (SafepointMechanism::uses_global_page_poll() && int(iterations) == DeferPollingPageLoopCount) {
 320           guarantee (PageArmed == 0, "invariant") ;
 321           PageArmed = 1 ;
 322           os::make_polling_page_unreadable();
 323         }
 324 
 325         // Instead of (ncpus > 1) consider either (still_running < (ncpus + EPSILON)) or
 326         // ((still_running + _waiting_to_block - TryingToBlock)) < ncpus)
 327         ++steps ;
 328         if (ncpus > 1 && steps < SafepointSpinBeforeYield) {
 329           SpinPause() ;     // MP-Polite spin
 330         } else
 331           if (steps < DeferThrSuspendLoopCount) {
 332             os::naked_yield() ;
 333           } else {
 334             os::naked_short_sleep(1);
 335           }
 336 
 337         iterations ++ ;
 338       }
 339       assert(iterations < (uint)max_jint, "We have been iterating in the safepoint loop too long");


 449   EventSafepointEnd event;
 450   int safepoint_id = safepoint_counter(); // Keep the odd counter as "id"
 451 
 452   assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
 453   assert((_safepoint_counter & 0x1) == 1, "must be odd");
 454   _safepoint_counter ++;
 455   // memory fence isn't required here since an odd _safepoint_counter
 456   // value can do no harm and a fence is issued below anyway.
 457 
 458   DEBUG_ONLY(Thread* myThread = Thread::current();)
 459   assert(myThread->is_VM_thread(), "Only VM thread can execute a safepoint");
 460 
 461   if (PrintSafepointStatistics) {
 462     end_statistics(os::javaTimeNanos());
 463   }
 464 
 465 #ifdef ASSERT
 466   // A pending_exception cannot be installed during a safepoint.  The threads
 467   // may install an async exception after they come back from a safepoint into
 468   // pending_exception after they unblock.  But that should happen later.
 469   for (JavaThread *cur = Threads::first(); cur; cur = cur->next()) {
 470     assert (!(cur->has_pending_exception() &&
 471               cur->safepoint_state()->is_at_poll_safepoint()),
 472             "safepoint installed a pending exception");
 473   }
 474 #endif // ASSERT
 475 
 476   if (PageArmed) {
 477     assert(SafepointMechanism::uses_global_page_poll(), "sanity");
 478     // Make polling safepoint aware
 479     os::make_polling_page_readable();
 480     PageArmed = 0 ;
 481   }
 482 
 483   if (SafepointMechanism::uses_global_page_poll()) {
 484     // Remove safepoint check from interpreter
 485     Interpreter::ignore_safepoints();
 486   }
 487 
 488   {
 489     MutexLocker mu(Safepoint_lock);
 490 
 491     assert(_state == _synchronized, "must be synchronized before ending safepoint synchronization");
 492 
 493     if (SafepointMechanism::uses_thread_local_poll()) {
 494       _state = _not_synchronized;
 495       OrderAccess::storestore(); // global state -> local state
 496       for (JavaThread *current = Threads::first(); current; current = current->next()) {
 497         ThreadSafepointState* cur_state = current->safepoint_state();
 498         cur_state->restart(); // TSS _running
 499         SafepointMechanism::disarm_local_poll(current); // release store, local state -> polling page
 500       }
 501       log_debug(safepoint)("Leaving safepoint region");
 502     } else {
 503       // Set to not synchronized, so the threads will not go into the signal_thread_blocked method
 504       // when they get restarted.
 505       _state = _not_synchronized;
 506       OrderAccess::fence();
 507 
 508       log_debug(safepoint)("Leaving safepoint region");
 509 
 510       // Start suspended threads
 511       for (JavaThread *current = Threads::first(); current; current = current->next()) {
 512         // A problem occurring on Solaris is when attempting to restart threads
 513         // the first #cpus - 1 go well, but then the VMThread is preempted when we get
 514         // to the next one (since it has been running the longest).  We then have
 515         // to wait for a cpu to become available before we can continue restarting
 516         // threads.
 517         // FIXME: This causes the performance of the VM to degrade when active and with
 518         // large numbers of threads.  Apparently this is due to the synchronous nature
 519         // of suspending threads.
 520         //
 521         // TODO-FIXME: the comments above are vestigial and no longer apply.
 522         // Furthermore, using solaris' schedctl in this particular context confers no benefit
 523         if (VMThreadHintNoPreempt) {
 524           os::hint_no_preempt();
 525         }
 526         ThreadSafepointState* cur_state = current->safepoint_state();
 527         assert(cur_state->type() != ThreadSafepointState::_running, "Thread not suspended at safepoint");
 528         cur_state->restart();
 529         assert(cur_state->is_running(), "safepoint state has not been reset");
 530       }
 531     }
 532 
 533     RuntimeService::record_safepoint_end();
 534 
 535     // Release threads lock, so threads can be created/destroyed again. It will also starts all threads
 536     // blocked in signal_thread_blocked
 537     Threads_lock->unlock();
 538 
 539   }
 540 #if INCLUDE_ALL_GCS
 541   // If there are any concurrent GC threads resume them.
 542   if (UseConcMarkSweepGC) {
 543     ConcurrentMarkSweepThread::desynchronize(false);
 544   } else if (UseG1GC) {
 545     SuspendibleThreadSet::desynchronize();
 546   }
 547 #endif // INCLUDE_ALL_GCS
 548   // record this time so VMThread can keep track how much time has elapsed
 549   // since last safepoint.
 550   _end_of_last_safepoint = os::javaTimeMillis();
 551 


 873   // We don't deliver an async exception if the thread state is
 874   // _thread_in_native_trans so JNI functions won't be called with
 875   // a surprising pending exception. If the thread state is going back to java,
 876   // async exception is checked in check_special_condition_for_native_trans().
 877 
 878   if (state != _thread_blocked_trans &&
 879       state != _thread_in_vm_trans &&
 880       thread->has_special_runtime_exit_condition()) {
 881     thread->handle_special_runtime_exit_condition(
 882       !thread->is_at_poll_safepoint() && (state != _thread_in_native_trans));
 883   }
 884 }
 885 
 886 // ------------------------------------------------------------------------------------------------------
 887 // Exception handlers
 888 
 889 
 890 void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
 891   assert(thread->is_Java_thread(), "polling reference encountered by VM thread");
 892   assert(thread->thread_state() == _thread_in_Java, "should come from Java code");
 893   if (!ThreadLocalHandshakes) {
 894     assert(SafepointSynchronize::is_synchronizing(), "polling encountered outside safepoint synchronization");
 895   }
 896 
 897   if (ShowSafepointMsgs) {
 898     tty->print("handle_polling_page_exception: ");
 899   }
 900 
 901   if (PrintSafepointStatistics) {
 902     inc_page_trap_count();
 903   }
 904 
 905   ThreadSafepointState* state = thread->safepoint_state();
 906 
 907   state->handle_polling_page_exception();
 908 }
 909 
 910 
 911 void SafepointSynchronize::print_safepoint_timeout(SafepointTimeoutReason reason) {
 912   if (!timeout_error_printed) {
 913     timeout_error_printed = true;
 914     // Print out the thread info which didn't reach the safepoint for debugging
 915     // purposes (useful when there are lots of threads in the debugger).
 916     tty->cr();
 917     tty->print_cr("# SafepointSynchronize::begin: Timeout detected:");
 918     if (reason ==  _spinning_timeout) {
 919       tty->print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint.");
 920     } else if (reason == _blocking_timeout) {
 921       tty->print_cr("# SafepointSynchronize::begin: Timed out while waiting for threads to stop.");
 922     }
 923 
 924     tty->print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:");
 925     ThreadSafepointState *cur_state;
 926     ResourceMark rm;
 927     for (JavaThread *cur_thread = Threads::first(); cur_thread;
 928         cur_thread = cur_thread->next()) {
 929       cur_state = cur_thread->safepoint_state();
 930 
 931       if (cur_thread->thread_state() != _thread_blocked &&
 932           ((reason == _spinning_timeout && cur_state->is_running()) ||
 933            (reason == _blocking_timeout && !cur_state->has_called_back()))) {
 934         tty->print("# ");
 935         cur_thread->print();
 936         tty->cr();
 937       }
 938     }
 939     tty->print_cr("# SafepointSynchronize::begin: (End of list)");
 940   }
 941 
 942   // To debug the long safepoint, specify both DieOnSafepointTimeout &
 943   // ShowMessageBoxOnError.
 944   if (DieOnSafepointTimeout) {
 945     fatal("Safepoint sync time longer than " INTX_FORMAT "ms detected when executing %s.",
 946           SafepointTimeoutDelay, VMThread::vm_safepoint_description());
 947   }


1073   const char *s = NULL;
1074 
1075   switch(_type) {
1076     case _running                : s = "_running";              break;
1077     case _at_safepoint           : s = "_at_safepoint";         break;
1078     case _call_back              : s = "_call_back";            break;
1079     default:
1080       ShouldNotReachHere();
1081   }
1082 
1083   st->print_cr("Thread: " INTPTR_FORMAT
1084               "  [0x%2x] State: %s _has_called_back %d _at_poll_safepoint %d",
1085                p2i(_thread), _thread->osthread()->thread_id(), s, _has_called_back,
1086                _at_poll_safepoint);
1087 
1088   _thread->print_thread_state_on(st);
1089 }
1090 
1091 // ---------------------------------------------------------------------------------------------------------------------
1092 
1093 // Block the thread at poll or poll return for safepoint/handshake.
1094 void ThreadSafepointState::handle_polling_page_exception() {
1095 
1096   // Check state.  block() will set thread state to thread_in_vm which will
1097   // cause the safepoint state _type to become _call_back.
1098   suspend_type t = type();
1099   assert(!SafepointMechanism::uses_global_page_poll() || t == ThreadSafepointState::_running,
1100          "polling page exception on thread not running state: %u", uint(t));
1101 
1102   // Step 1: Find the nmethod from the return address
1103   if (ShowSafepointMsgs && Verbose) {
1104     tty->print_cr("Polling page exception at " INTPTR_FORMAT, p2i(thread()->saved_exception_pc()));
1105   }
1106   address real_return_addr = thread()->saved_exception_pc();
1107 
1108   CodeBlob *cb = CodeCache::find_blob(real_return_addr);
1109   assert(cb != NULL && cb->is_compiled(), "return address should be in nmethod");
1110   CompiledMethod* nm = (CompiledMethod*)cb;
1111 
1112   // Find frame of caller
1113   frame stub_fr = thread()->last_frame();
1114   CodeBlob* stub_cb = stub_fr.cb();
1115   assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub");
1116   RegisterMap map(thread(), true);
1117   frame caller_fr = stub_fr.sender(&map);
1118 
1119   // Should only be poll_return or poll
1120   assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" );


1122   // This is a poll immediately before a return. The exception handling code
1123   // has already had the effect of causing the return to occur, so the execution
1124   // will continue immediately after the call. In addition, the oopmap at the
1125   // return point does not mark the return value as an oop (if it is), so
1126   // it needs a handle here to be updated.
1127   if( nm->is_at_poll_return(real_return_addr) ) {
1128     // See if return type is an oop.
1129     bool return_oop = nm->method()->is_returning_oop();
1130     Handle return_value;
1131     if (return_oop) {
1132       // The oop result has been saved on the stack together with all
1133       // the other registers. In order to preserve it over GCs we need
1134       // to keep it in a handle.
1135       oop result = caller_fr.saved_oop_result(&map);
1136       assert(oopDesc::is_oop_or_null(result), "must be oop");
1137       return_value = Handle(thread(), result);
1138       assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
1139     }
1140 
1141     // Block the thread
1142     SafepointMechanism::block_if_requested(thread());
1143 
1144     // restore oop result, if any
1145     if (return_oop) {
1146       caller_fr.set_saved_oop_result(&map, return_value());
1147     }
1148   }
1149 
1150   // This is a safepoint poll. Verify the return address and block.
1151   else {
1152     set_at_poll_safepoint(true);
1153 
1154     // verify the blob built the "return address" correctly
1155     assert(real_return_addr == caller_fr.pc(), "must match");
1156 
1157     // Block the thread
1158     SafepointMechanism::block_if_requested(thread());
1159     set_at_poll_safepoint(false);
1160 
1161     // If we have a pending async exception deoptimize the frame
1162     // as otherwise we may never deliver it.
1163     if (thread()->has_async_condition()) {
1164       ThreadInVMfromJavaNoAsyncException __tiv(thread());
1165       Deoptimization::deoptimize_frame(thread(), caller_fr.id());
1166     }
1167 
1168     // If an exception has been installed we must check for a pending deoptimization
1169     // Deoptimize frame if exception has been thrown.
1170 
1171     if (thread()->has_pending_exception() ) {
1172       RegisterMap map(thread(), true);
1173       frame caller_fr = stub_fr.sender(&map);
1174       if (caller_fr.is_deoptimized_frame()) {
1175         // The exception patch will destroy registers that are still
1176         // live and will be needed during deoptimization. Defer the
1177         // Async exception should have deferred the exception until the
1178         // next safepoint which will be detected when we get into


1419                 _coalesced_vmop_count);
1420   tty->print_cr("Maximum sync time  " INT64_FORMAT_W(5) " ms",
1421                 (int64_t)(_max_sync_time / MICROUNITS));
1422   tty->print_cr("Maximum vm operation time (except for Exit VM operation)  "
1423                 INT64_FORMAT_W(5) " ms",
1424                 (int64_t)(_max_vmop_time / MICROUNITS));
1425 }
1426 
1427 // ------------------------------------------------------------------------------------------------
1428 // Non-product code
1429 
1430 #ifndef PRODUCT
1431 
1432 void SafepointSynchronize::print_state() {
1433   if (_state == _not_synchronized) {
1434     tty->print_cr("not synchronized");
1435   } else if (_state == _synchronizing || _state == _synchronized) {
1436     tty->print_cr("State: %s", (_state == _synchronizing) ? "synchronizing" :
1437                   "synchronized");
1438 
1439     for (JavaThread *cur = Threads::first(); cur; cur = cur->next()) {
1440        cur->safepoint_state()->print();
1441     }
1442   }
1443 }
1444 
1445 void SafepointSynchronize::safepoint_msg(const char* format, ...) {
1446   if (ShowSafepointMsgs) {
1447     va_list ap;
1448     va_start(ap, format);
1449     tty->vprint_cr(format, ap);
1450     va_end(ap);
1451   }
1452 }
1453 
1454 #endif // !PRODUCT
< prev index next >