1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/symbolTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "code/nmethod.hpp"
  31 #include "code/pcDesc.hpp"
  32 #include "code/scopeDesc.hpp"
  33 #include "gc_interface/collectedHeap.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "jfr/jfrEvents.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "memory/universe.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "oops/symbol.hpp"
  40 #include "runtime/compilationPolicy.hpp"
  41 #include "runtime/deoptimization.hpp"
  42 #include "runtime/frame.inline.hpp"
  43 #include "runtime/interfaceSupport.hpp"
  44 #include "runtime/mutexLocker.hpp"
  45 #include "runtime/orderAccess.inline.hpp"
  46 #include "runtime/osThread.hpp"
  47 #include "runtime/safepoint.hpp"
  48 #include "runtime/signature.hpp"
  49 #include "runtime/stubCodeGenerator.hpp"
  50 #include "runtime/stubRoutines.hpp"
  51 #include "runtime/sweeper.hpp"
  52 #include "runtime/synchronizer.hpp"
  53 #include "runtime/thread.inline.hpp"
  54 #include "services/runtimeService.hpp"
  55 #include "utilities/events.hpp"
  56 #include "utilities/macros.hpp"
  57 #ifdef TARGET_ARCH_x86
  58 # include "nativeInst_x86.hpp"
  59 # include "vmreg_x86.inline.hpp"
  60 #endif
  61 #ifdef TARGET_ARCH_aarch64
  62 # include "nativeInst_aarch64.hpp"
  63 # include "vmreg_aarch64.inline.hpp"
  64 #endif
  65 #ifdef TARGET_ARCH_sparc
  66 # include "nativeInst_sparc.hpp"
  67 # include "vmreg_sparc.inline.hpp"
  68 #endif
  69 #ifdef TARGET_ARCH_zero
  70 # include "nativeInst_zero.hpp"
  71 # include "vmreg_zero.inline.hpp"
  72 #endif
  73 #ifdef TARGET_ARCH_arm
  74 # include "nativeInst_arm.hpp"
  75 # include "vmreg_arm.inline.hpp"
  76 #endif
  77 #ifdef TARGET_ARCH_ppc
  78 # include "nativeInst_ppc.hpp"
  79 # include "vmreg_ppc.inline.hpp"
  80 #endif
  81 #if INCLUDE_ALL_GCS
  82 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
  83 #include "gc_implementation/shared/suspendibleThreadSet.hpp"
  84 #endif // INCLUDE_ALL_GCS
  85 #ifdef COMPILER1
  86 #include "c1/c1_globals.hpp"
  87 #endif
  88 
  89 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  90 
  91 template <typename E>
  92 static void set_current_safepoint_id(E* event, int adjustment = 0) {
  93   assert(event != NULL, "invariant");
  94   event->set_safepointId(SafepointSynchronize::safepoint_counter() + adjustment);
  95 }
  96 
  97 static void post_safepoint_begin_event(EventSafepointBegin* event,
  98                                        int thread_count,
  99                                        int critical_thread_count) {
 100   assert(event != NULL, "invariant");
 101   assert(event->should_commit(), "invariant");
 102   set_current_safepoint_id(event);
 103   event->set_totalThreadCount(thread_count);
 104   event->set_jniCriticalThreadCount(critical_thread_count);
 105   event->commit();
 106 }
 107 
 108 static void post_safepoint_cleanup_event(EventSafepointCleanup* event) {
 109   assert(event != NULL, "invariant");
 110   assert(event->should_commit(), "invariant");
 111   set_current_safepoint_id(event);
 112   event->commit();
 113 }
 114 
 115 static void post_safepoint_synchronize_event(EventSafepointStateSynchronization* event,
 116                                              int initial_number_of_threads,
 117                                              int threads_waiting_to_block,
 118                                              unsigned int iterations) {
 119   assert(event != NULL, "invariant");
 120   if (event->should_commit()) {
 121     // Group this event together with the ones committed after the counter is increased
 122     set_current_safepoint_id(event, 1);
 123     event->set_initialThreadCount(initial_number_of_threads);
 124     event->set_runningThreadCount(threads_waiting_to_block);
 125     event->set_iterations(iterations);
 126     event->commit();
 127   }
 128 }
 129 
 130 static void post_safepoint_wait_blocked_event(EventSafepointWaitBlocked* event,
 131                                               int initial_threads_waiting_to_block) {
 132   assert(event != NULL, "invariant");
 133   assert(event->should_commit(), "invariant");
 134   set_current_safepoint_id(event);
 135   event->set_runningThreadCount(initial_threads_waiting_to_block);
 136   event->commit();
 137 }
 138 
 139 static void post_safepoint_cleanup_task_event(EventSafepointCleanupTask* event,
 140                                               const char* name) {
 141   assert(event != NULL, "invariant");
 142   if (event->should_commit()) {
 143     set_current_safepoint_id(event);
 144     event->set_name(name);
 145     event->commit();
 146   }
 147 }
 148 
 149 static void post_safepoint_end_event(EventSafepointEnd* event) {
 150   assert(event != NULL, "invariant");
 151   if (event->should_commit()) {
 152     // Group this event together with the ones committed before the counter increased
 153     set_current_safepoint_id(event, -1);
 154     event->commit();
 155   }
 156 }
 157 
 158 // --------------------------------------------------------------------------------------------------
 159 // Implementation of Safepoint begin/end
 160 
 161 SafepointSynchronize::SynchronizeState volatile SafepointSynchronize::_state = SafepointSynchronize::_not_synchronized;
 162 volatile int  SafepointSynchronize::_waiting_to_block = 0;
 163 volatile int SafepointSynchronize::_safepoint_counter = 0;
 164 int SafepointSynchronize::_current_jni_active_count = 0;
 165 long  SafepointSynchronize::_end_of_last_safepoint = 0;
 166 static volatile int PageArmed = 0 ;        // safepoint polling page is RO|RW vs PROT_NONE
 167 static volatile int TryingToBlock = 0 ;    // proximate value -- for advisory use only
 168 static bool timeout_error_printed = false;
 169 
 170 // Roll all threads forward to a safepoint and suspend them all
 171 void SafepointSynchronize::begin() {
 172   EventSafepointBegin begin_event;
 173   Thread* myThread = Thread::current();
 174   assert(myThread->is_VM_thread(), "Only VM thread may execute a safepoint");
 175 
 176   if (PrintSafepointStatistics || PrintSafepointStatisticsTimeout > 0) {
 177     _safepoint_begin_time = os::javaTimeNanos();
 178     _ts_of_current_safepoint = tty->time_stamp().seconds();
 179   }
 180 
 181 #if INCLUDE_ALL_GCS
 182   if (UseConcMarkSweepGC) {
 183     // In the future we should investigate whether CMS can use the
 184     // more-general mechanism below.  DLD (01/05).
 185     ConcurrentMarkSweepThread::synchronize(false);
 186   } else if (UseG1GC || (UseShenandoahGC && UseStringDeduplication)) {
 187     SuspendibleThreadSet::synchronize();
 188   }
 189 #endif // INCLUDE_ALL_GCS
 190 
 191   // By getting the Threads_lock, we assure that no threads are about to start or
 192   // exit. It is released again in SafepointSynchronize::end().
 193   Threads_lock->lock();
 194 
 195   assert( _state == _not_synchronized, "trying to safepoint synchronize with wrong state");
 196 
 197   int nof_threads = Threads::number_of_threads();
 198 
 199   if (TraceSafepoint) {
 200     tty->print_cr("Safepoint synchronization initiated. (%d)", nof_threads);
 201   }
 202 
 203   RuntimeService::record_safepoint_begin();
 204 
 205   MutexLocker mu(Safepoint_lock);
 206 
 207   // Reset the count of active JNI critical threads
 208   _current_jni_active_count = 0;
 209 
 210   // Set number of threads to wait for, before we initiate the callbacks
 211   _waiting_to_block = nof_threads;
 212   TryingToBlock     = 0 ;
 213   int still_running = nof_threads;
 214 
 215   // Save the starting time, so that it can be compared to see if this has taken
 216   // too long to complete.
 217   jlong safepoint_limit_time = 0;
 218   timeout_error_printed = false;
 219 
 220   // PrintSafepointStatisticsTimeout can be specified separately. When
 221   // specified, PrintSafepointStatistics will be set to true in
 222   // deferred_initialize_stat method. The initialization has to be done
 223   // early enough to avoid any races. See bug 6880029 for details.
 224   if (PrintSafepointStatistics || PrintSafepointStatisticsTimeout > 0) {
 225     deferred_initialize_stat();
 226   }
 227 
 228   // Begin the process of bringing the system to a safepoint.
 229   // Java threads can be in several different states and are
 230   // stopped by different mechanisms:
 231   //
 232   //  1. Running interpreted
 233   //     The interpeter dispatch table is changed to force it to
 234   //     check for a safepoint condition between bytecodes.
 235   //  2. Running in native code
 236   //     When returning from the native code, a Java thread must check
 237   //     the safepoint _state to see if we must block.  If the
 238   //     VM thread sees a Java thread in native, it does
 239   //     not wait for this thread to block.  The order of the memory
 240   //     writes and reads of both the safepoint state and the Java
 241   //     threads state is critical.  In order to guarantee that the
 242   //     memory writes are serialized with respect to each other,
 243   //     the VM thread issues a memory barrier instruction
 244   //     (on MP systems).  In order to avoid the overhead of issuing
 245   //     a memory barrier for each Java thread making native calls, each Java
 246   //     thread performs a write to a single memory page after changing
 247   //     the thread state.  The VM thread performs a sequence of
 248   //     mprotect OS calls which forces all previous writes from all
 249   //     Java threads to be serialized.  This is done in the
 250   //     os::serialize_thread_states() call.  This has proven to be
 251   //     much more efficient than executing a membar instruction
 252   //     on every call to native code.
 253   //  3. Running compiled Code
 254   //     Compiled code reads a global (Safepoint Polling) page that
 255   //     is set to fault if we are trying to get to a safepoint.
 256   //  4. Blocked
 257   //     A thread which is blocked will not be allowed to return from the
 258   //     block condition until the safepoint operation is complete.
 259   //  5. In VM or Transitioning between states
 260   //     If a Java thread is currently running in the VM or transitioning
 261   //     between states, the safepointing code will wait for the thread to
 262   //     block itself when it attempts transitions to a new state.
 263   //
 264   EventSafepointStateSynchronization sync_event;
 265   int initial_running = 0;
 266 
 267   _state            = _synchronizing;
 268   OrderAccess::fence();
 269 
 270   // Flush all thread states to memory
 271   if (!UseMembar) {
 272     os::serialize_thread_states();
 273   }
 274 
 275   // Make interpreter safepoint aware
 276   Interpreter::notice_safepoints();
 277 
 278   if (UseCompilerSafepoints && DeferPollingPageLoopCount < 0) {
 279     // Make polling safepoint aware
 280     guarantee (PageArmed == 0, "invariant") ;
 281     PageArmed = 1 ;
 282     os::make_polling_page_unreadable();
 283   }
 284 
 285   // Consider using active_processor_count() ... but that call is expensive.
 286   int ncpus = os::processor_count() ;
 287 
 288 #ifdef ASSERT
 289   for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) {
 290     assert(cur->safepoint_state()->is_running(), "Illegal initial state");
 291     // Clear the visited flag to ensure that the critical counts are collected properly.
 292     cur->set_visited_for_critical_count(false);
 293   }
 294 #endif // ASSERT
 295 
 296   if (SafepointTimeout)
 297     safepoint_limit_time = os::javaTimeNanos() + (jlong)SafepointTimeoutDelay * MICROUNITS;
 298 
 299   // Iterate through all threads until it have been determined how to stop them all at a safepoint
 300   unsigned int iterations = 0;
 301   int steps = 0 ;
 302   while(still_running > 0) {
 303     for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) {
 304       assert(!cur->is_ConcurrentGC_thread(), "A concurrent GC thread is unexpectly being suspended");
 305       ThreadSafepointState *cur_state = cur->safepoint_state();
 306       if (cur_state->is_running()) {
 307         cur_state->examine_state_of_thread();
 308         if (!cur_state->is_running()) {
 309            still_running--;
 310            // consider adjusting steps downward:
 311            //   steps = 0
 312            //   steps -= NNN
 313            //   steps >>= 1
 314            //   steps = MIN(steps, 2000-100)
 315            //   if (iterations != 0) steps -= NNN
 316         }
 317         if (TraceSafepoint && Verbose) cur_state->print();
 318       }
 319     }
 320 
 321     if (iterations == 0) {
 322       initial_running = still_running;
 323       if (PrintSafepointStatistics) {
 324         begin_statistics(nof_threads, still_running);
 325       }
 326     }
 327 
 328     if (still_running > 0) {
 329       // Check for if it takes to long
 330       if (SafepointTimeout && safepoint_limit_time < os::javaTimeNanos()) {
 331         print_safepoint_timeout(_spinning_timeout);
 332       }
 333 
 334       // Spin to avoid context switching.
 335       // There's a tension between allowing the mutators to run (and rendezvous)
 336       // vs spinning.  As the VM thread spins, wasting cycles, it consumes CPU that
 337       // a mutator might otherwise use profitably to reach a safepoint.  Excessive
 338       // spinning by the VM thread on a saturated system can increase rendezvous latency.
 339       // Blocking or yielding incur their own penalties in the form of context switching
 340       // and the resultant loss of $ residency.
 341       //
 342       // Further complicating matters is that yield() does not work as naively expected
 343       // on many platforms -- yield() does not guarantee that any other ready threads
 344       // will run.   As such we revert yield_all() after some number of iterations.
 345       // Yield_all() is implemented as a short unconditional sleep on some platforms.
 346       // Typical operating systems round a "short" sleep period up to 10 msecs, so sleeping
 347       // can actually increase the time it takes the VM thread to detect that a system-wide
 348       // stop-the-world safepoint has been reached.  In a pathological scenario such as that
 349       // described in CR6415670 the VMthread may sleep just before the mutator(s) become safe.
 350       // In that case the mutators will be stalled waiting for the safepoint to complete and the
 351       // the VMthread will be sleeping, waiting for the mutators to rendezvous.  The VMthread
 352       // will eventually wake up and detect that all mutators are safe, at which point
 353       // we'll again make progress.
 354       //
 355       // Beware too that that the VMThread typically runs at elevated priority.
 356       // Its default priority is higher than the default mutator priority.
 357       // Obviously, this complicates spinning.
 358       //
 359       // Note too that on Windows XP SwitchThreadTo() has quite different behavior than Sleep(0).
 360       // Sleep(0) will _not yield to lower priority threads, while SwitchThreadTo() will.
 361       //
 362       // See the comments in synchronizer.cpp for additional remarks on spinning.
 363       //
 364       // In the future we might:
 365       // 1. Modify the safepoint scheme to avoid potentally unbounded spinning.
 366       //    This is tricky as the path used by a thread exiting the JVM (say on
 367       //    on JNI call-out) simply stores into its state field.  The burden
 368       //    is placed on the VM thread, which must poll (spin).
 369       // 2. Find something useful to do while spinning.  If the safepoint is GC-related
 370       //    we might aggressively scan the stacks of threads that are already safe.
 371       // 3. Use Solaris schedctl to examine the state of the still-running mutators.
 372       //    If all the mutators are ONPROC there's no reason to sleep or yield.
 373       // 4. YieldTo() any still-running mutators that are ready but OFFPROC.
 374       // 5. Check system saturation.  If the system is not fully saturated then
 375       //    simply spin and avoid sleep/yield.
 376       // 6. As still-running mutators rendezvous they could unpark the sleeping
 377       //    VMthread.  This works well for still-running mutators that become
 378       //    safe.  The VMthread must still poll for mutators that call-out.
 379       // 7. Drive the policy on time-since-begin instead of iterations.
 380       // 8. Consider making the spin duration a function of the # of CPUs:
 381       //    Spin = (((ncpus-1) * M) + K) + F(still_running)
 382       //    Alternately, instead of counting iterations of the outer loop
 383       //    we could count the # of threads visited in the inner loop, above.
 384       // 9. On windows consider using the return value from SwitchThreadTo()
 385       //    to drive subsequent spin/SwitchThreadTo()/Sleep(N) decisions.
 386 
 387       if (UseCompilerSafepoints && int(iterations) == DeferPollingPageLoopCount) {
 388          guarantee (PageArmed == 0, "invariant") ;
 389          PageArmed = 1 ;
 390          os::make_polling_page_unreadable();
 391       }
 392 
 393       // Instead of (ncpus > 1) consider either (still_running < (ncpus + EPSILON)) or
 394       // ((still_running + _waiting_to_block - TryingToBlock)) < ncpus)
 395       ++steps ;
 396       if (ncpus > 1 && steps < SafepointSpinBeforeYield) {
 397         SpinPause() ;     // MP-Polite spin
 398       } else
 399       if (steps < DeferThrSuspendLoopCount) {
 400         os::NakedYield() ;
 401       } else {
 402         os::yield_all(steps) ;
 403         // Alternately, the VM thread could transiently depress its scheduling priority or
 404         // transiently increase the priority of the tardy mutator(s).
 405       }
 406 
 407       iterations ++ ;
 408     }
 409     assert(iterations < (uint)max_jint, "We have been iterating in the safepoint loop too long");
 410   }
 411   assert(still_running == 0, "sanity check");
 412 
 413   if (PrintSafepointStatistics) {
 414     update_statistics_on_spin_end();
 415   }
 416 
 417   if (sync_event.should_commit()) {
 418     post_safepoint_synchronize_event(&sync_event, initial_running, _waiting_to_block, iterations);
 419   }
 420 
 421   // wait until all threads are stopped
 422   {
 423     EventSafepointWaitBlocked wait_blocked_event;
 424     int initial_waiting_to_block = _waiting_to_block;
 425 
 426     while (_waiting_to_block > 0) {
 427       if (TraceSafepoint) tty->print_cr("Waiting for %d thread(s) to block", _waiting_to_block);
 428       if (!SafepointTimeout || timeout_error_printed) {
 429         Safepoint_lock->wait(true);  // true, means with no safepoint checks
 430       } else {
 431         // Compute remaining time
 432         jlong remaining_time = safepoint_limit_time - os::javaTimeNanos();
 433 
 434         // If there is no remaining time, then there is an error
 435         if (remaining_time < 0 || Safepoint_lock->wait(true, remaining_time / MICROUNITS)) {
 436           print_safepoint_timeout(_blocking_timeout);
 437         }
 438       }
 439     }
 440     assert(_waiting_to_block == 0, "sanity check");
 441 
 442 #ifndef PRODUCT
 443     if (SafepointTimeout) {
 444       jlong current_time = os::javaTimeNanos();
 445       if (safepoint_limit_time < current_time) {
 446         tty->print_cr("# SafepointSynchronize: Finished after "
 447                       INT64_FORMAT_W(6) " ms",
 448                       ((current_time - safepoint_limit_time) / MICROUNITS +
 449                        SafepointTimeoutDelay));
 450       }
 451     }
 452 #endif
 453 
 454     assert((_safepoint_counter & 0x1) == 0, "must be even");
 455     assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
 456     _safepoint_counter ++;
 457 
 458     // Record state
 459     _state = _synchronized;
 460 
 461     OrderAccess::fence();
 462 
 463     if (wait_blocked_event.should_commit()) {
 464       post_safepoint_wait_blocked_event(&wait_blocked_event, initial_waiting_to_block);
 465     }
 466   }
 467 
 468 #ifdef ASSERT
 469   for (JavaThread *cur = Threads::first(); cur != NULL; cur = cur->next()) {
 470     // make sure all the threads were visited
 471     assert(cur->was_visited_for_critical_count(), "missed a thread");
 472   }
 473 #endif // ASSERT
 474 
 475   // Update the count of active JNI critical regions
 476   GC_locker::set_jni_lock_count(_current_jni_active_count);
 477 
 478   if (TraceSafepoint) {
 479     VM_Operation *op = VMThread::vm_operation();
 480     tty->print_cr("Entering safepoint region: %s", (op != NULL) ? op->name() : "no vm operation");
 481   }
 482 
 483   RuntimeService::record_safepoint_synchronized();
 484   if (PrintSafepointStatistics) {
 485     update_statistics_on_sync_end(os::javaTimeNanos());
 486   }
 487 
 488   // Call stuff that needs to be run when a safepoint is just about to be completed
 489   {
 490     EventSafepointCleanup cleanup_event;
 491     do_cleanup_tasks();
 492     if (cleanup_event.should_commit()) {
 493       post_safepoint_cleanup_event(&cleanup_event);
 494     }
 495   }
 496 
 497   if (PrintSafepointStatistics) {
 498     // Record how much time spend on the above cleanup tasks
 499     update_statistics_on_cleanup_end(os::javaTimeNanos());
 500   }
 501 
 502   if (begin_event.should_commit()) {
 503     post_safepoint_begin_event(&begin_event, nof_threads, _current_jni_active_count);
 504   }
 505 }
 506 
 507 // Wake up all threads, so they are ready to resume execution after the safepoint
 508 // operation has been carried out
 509 void SafepointSynchronize::end() {
 510 
 511   assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
 512   assert((_safepoint_counter & 0x1) == 1, "must be odd");
 513   EventSafepointEnd event;
 514   _safepoint_counter ++;
 515   // memory fence isn't required here since an odd _safepoint_counter
 516   // value can do no harm and a fence is issued below anyway.
 517 
 518   DEBUG_ONLY(Thread* myThread = Thread::current();)
 519   assert(myThread->is_VM_thread(), "Only VM thread can execute a safepoint");
 520 
 521   if (PrintSafepointStatistics) {
 522     end_statistics(os::javaTimeNanos());
 523   }
 524 
 525 #ifdef ASSERT
 526   // A pending_exception cannot be installed during a safepoint.  The threads
 527   // may install an async exception after they come back from a safepoint into
 528   // pending_exception after they unblock.  But that should happen later.
 529   for(JavaThread *cur = Threads::first(); cur; cur = cur->next()) {
 530     assert (!(cur->has_pending_exception() &&
 531               cur->safepoint_state()->is_at_poll_safepoint()),
 532             "safepoint installed a pending exception");
 533   }
 534 #endif // ASSERT
 535 
 536   if (PageArmed) {
 537     // Make polling safepoint aware
 538     os::make_polling_page_readable();
 539     PageArmed = 0 ;
 540   }
 541 
 542   // Remove safepoint check from interpreter
 543   Interpreter::ignore_safepoints();
 544 
 545   {
 546     MutexLocker mu(Safepoint_lock);
 547 
 548     assert(_state == _synchronized, "must be synchronized before ending safepoint synchronization");
 549 
 550     // Set to not synchronized, so the threads will not go into the signal_thread_blocked method
 551     // when they get restarted.
 552     _state = _not_synchronized;
 553     OrderAccess::fence();
 554 
 555     if (TraceSafepoint) {
 556        tty->print_cr("Leaving safepoint region");
 557     }
 558 
 559     // Start suspended threads
 560     for(JavaThread *current = Threads::first(); current; current = current->next()) {
 561       // A problem occurring on Solaris is when attempting to restart threads
 562       // the first #cpus - 1 go well, but then the VMThread is preempted when we get
 563       // to the next one (since it has been running the longest).  We then have
 564       // to wait for a cpu to become available before we can continue restarting
 565       // threads.
 566       // FIXME: This causes the performance of the VM to degrade when active and with
 567       // large numbers of threads.  Apparently this is due to the synchronous nature
 568       // of suspending threads.
 569       //
 570       // TODO-FIXME: the comments above are vestigial and no longer apply.
 571       // Furthermore, using solaris' schedctl in this particular context confers no benefit
 572       if (VMThreadHintNoPreempt) {
 573         os::hint_no_preempt();
 574       }
 575       ThreadSafepointState* cur_state = current->safepoint_state();
 576       assert(cur_state->type() != ThreadSafepointState::_running, "Thread not suspended at safepoint");
 577       cur_state->restart();
 578       assert(cur_state->is_running(), "safepoint state has not been reset");
 579     }
 580 
 581     RuntimeService::record_safepoint_end();
 582 
 583     // Release threads lock, so threads can be created/destroyed again. It will also starts all threads
 584     // blocked in signal_thread_blocked
 585     Threads_lock->unlock();
 586 
 587   }
 588 #if INCLUDE_ALL_GCS
 589   // If there are any concurrent GC threads resume them.
 590   if (UseConcMarkSweepGC) {
 591     ConcurrentMarkSweepThread::desynchronize(false);
 592   } else if (UseG1GC || (UseShenandoahGC && UseStringDeduplication)) {
 593     SuspendibleThreadSet::desynchronize();
 594   }
 595 #endif // INCLUDE_ALL_GCS
 596   // record this time so VMThread can keep track how much time has elasped
 597   // since last safepoint.
 598   _end_of_last_safepoint = os::javaTimeMillis();
 599   if (event.should_commit()) {
 600     post_safepoint_end_event(&event);
 601   }
 602 }
 603 
 604 bool SafepointSynchronize::is_cleanup_needed() {
 605   // Need a safepoint if some inline cache buffers is non-empty
 606   if (!InlineCacheBuffer::is_empty()) return true;
 607   return false;
 608 }
 609 
 610 
 611 
 612 // Various cleaning tasks that should be done periodically at safepoints
 613 void SafepointSynchronize::do_cleanup_tasks() {
 614   {
 615     const char* name = "deflating idle monitors";
 616     EventSafepointCleanupTask event;
 617     TraceTime t1(name, TraceSafepointCleanupTime);
 618     ObjectSynchronizer::deflate_idle_monitors();
 619     if (event.should_commit()) {
 620       post_safepoint_cleanup_task_event(&event, name);
 621     }
 622   }
 623 
 624   {
 625     const char* name = "updating inline caches";
 626     EventSafepointCleanupTask event;
 627     TraceTime t2(name, TraceSafepointCleanupTime);
 628     InlineCacheBuffer::update_inline_caches();
 629     if (event.should_commit()) {
 630       post_safepoint_cleanup_task_event(&event, name);
 631     }
 632   }
 633   {
 634     const char* name = "compilation policy safepoint handler";
 635     EventSafepointCleanupTask event;
 636     TraceTime t3(name, TraceSafepointCleanupTime);
 637     CompilationPolicy::policy()->do_safepoint_work();
 638     if (event.should_commit()) {
 639       post_safepoint_cleanup_task_event(&event, name);
 640     }
 641   }
 642 
 643   {
 644     const char* name = "mark nmethods";
 645     EventSafepointCleanupTask event;
 646     TraceTime t4(name, TraceSafepointCleanupTime);
 647     NMethodSweeper::mark_active_nmethods();
 648     if (event.should_commit()) {
 649       post_safepoint_cleanup_task_event(&event, name);
 650     }
 651   }
 652 
 653   if (SymbolTable::needs_rehashing()) {
 654     const char* name = "rehashing symbol table";
 655     EventSafepointCleanupTask event;
 656     TraceTime t5(name, TraceSafepointCleanupTime);
 657     SymbolTable::rehash_table();
 658     if (event.should_commit()) {
 659       post_safepoint_cleanup_task_event(&event, name);
 660     }
 661   }
 662 
 663   if (StringTable::needs_rehashing()) {
 664     const char* name = "rehashing string table";
 665     EventSafepointCleanupTask event;
 666     TraceTime t6(name, TraceSafepointCleanupTime);
 667     StringTable::rehash_table();
 668     if (event.should_commit()) {
 669       post_safepoint_cleanup_task_event(&event, name);
 670     }
 671   }
 672 
 673   // rotate log files?
 674   if (UseGCLogFileRotation) {
 675     TraceTime t8("rotating gc logs", TraceSafepointCleanupTime);
 676     gclog_or_tty->rotate_log(false);
 677   }
 678 
 679   {
 680     // CMS delays purging the CLDG until the beginning of the next safepoint and to
 681     // make sure concurrent sweep is done
 682     TraceTime t7("purging class loader data graph", TraceSafepointCleanupTime);
 683     ClassLoaderDataGraph::purge_if_needed();
 684   }
 685 }
 686 
 687 
 688 bool SafepointSynchronize::safepoint_safe(JavaThread *thread, JavaThreadState state) {
 689   switch(state) {
 690   case _thread_in_native:
 691     // native threads are safe if they have no java stack or have walkable stack
 692     return !thread->has_last_Java_frame() || thread->frame_anchor()->walkable();
 693 
 694    // blocked threads should have already have walkable stack
 695   case _thread_blocked:
 696     assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "blocked and not walkable");
 697     return true;
 698 
 699   default:
 700     return false;
 701   }
 702 }
 703 
 704 
 705 // See if the thread is running inside a lazy critical native and
 706 // update the thread critical count if so.  Also set a suspend flag to
 707 // cause the native wrapper to return into the JVM to do the unlock
 708 // once the native finishes.
 709 void SafepointSynchronize::check_for_lazy_critical_native(JavaThread *thread, JavaThreadState state) {
 710   if (state == _thread_in_native &&
 711       thread->has_last_Java_frame() &&
 712       thread->frame_anchor()->walkable()) {
 713     // This thread might be in a critical native nmethod so look at
 714     // the top of the stack and increment the critical count if it
 715     // is.
 716     frame wrapper_frame = thread->last_frame();
 717     CodeBlob* stub_cb = wrapper_frame.cb();
 718     if (stub_cb != NULL &&
 719         stub_cb->is_nmethod() &&
 720         stub_cb->as_nmethod_or_null()->is_lazy_critical_native()) {
 721       // A thread could potentially be in a critical native across
 722       // more than one safepoint, so only update the critical state on
 723       // the first one.  When it returns it will perform the unlock.
 724       if (!thread->do_critical_native_unlock()) {
 725 #ifdef ASSERT
 726         if (!thread->in_critical()) {
 727           GC_locker::increment_debug_jni_lock_count();
 728         }
 729 #endif
 730         thread->enter_critical();
 731         // Make sure the native wrapper calls back on return to
 732         // perform the needed critical unlock.
 733         thread->set_critical_native_unlock();
 734       }
 735     }
 736   }
 737 }
 738 
 739 
 740 
 741 // -------------------------------------------------------------------------------------------------------
 742 // Implementation of Safepoint callback point
 743 
 744 void SafepointSynchronize::block(JavaThread *thread) {
 745   assert(thread != NULL, "thread must be set");
 746   assert(thread->is_Java_thread(), "not a Java thread");
 747 
 748   // Threads shouldn't block if they are in the middle of printing, but...
 749   ttyLocker::break_tty_lock_for_safepoint(os::current_thread_id());
 750 
 751   // Only bail from the block() call if the thread is gone from the
 752   // thread list; starting to exit should still block.
 753   if (thread->is_terminated()) {
 754      // block current thread if we come here from native code when VM is gone
 755      thread->block_if_vm_exited();
 756 
 757      // otherwise do nothing
 758      return;
 759   }
 760 
 761   JavaThreadState state = thread->thread_state();
 762   thread->frame_anchor()->make_walkable(thread);
 763 
 764   // Check that we have a valid thread_state at this point
 765   switch(state) {
 766     case _thread_in_vm_trans:
 767     case _thread_in_Java:        // From compiled code
 768 
 769       // We are highly likely to block on the Safepoint_lock. In order to avoid blocking in this case,
 770       // we pretend we are still in the VM.
 771       thread->set_thread_state(_thread_in_vm);
 772 
 773       if (is_synchronizing()) {
 774          Atomic::inc (&TryingToBlock) ;
 775       }
 776 
 777       // We will always be holding the Safepoint_lock when we are examine the state
 778       // of a thread. Hence, the instructions between the Safepoint_lock->lock() and
 779       // Safepoint_lock->unlock() are happening atomic with regards to the safepoint code
 780       Safepoint_lock->lock_without_safepoint_check();
 781       if (is_synchronizing()) {
 782         // Decrement the number of threads to wait for and signal vm thread
 783         assert(_waiting_to_block > 0, "sanity check");
 784         _waiting_to_block--;
 785         thread->safepoint_state()->set_has_called_back(true);
 786 
 787         DEBUG_ONLY(thread->set_visited_for_critical_count(true));
 788         if (thread->in_critical()) {
 789           // Notice that this thread is in a critical section
 790           increment_jni_active_count();
 791         }
 792 
 793         // Consider (_waiting_to_block < 2) to pipeline the wakeup of the VM thread
 794         if (_waiting_to_block == 0) {
 795           Safepoint_lock->notify_all();
 796         }
 797       }
 798 
 799       // We transition the thread to state _thread_blocked here, but
 800       // we can't do our usual check for external suspension and then
 801       // self-suspend after the lock_without_safepoint_check() call
 802       // below because we are often called during transitions while
 803       // we hold different locks. That would leave us suspended while
 804       // holding a resource which results in deadlocks.
 805       thread->set_thread_state(_thread_blocked);
 806       Safepoint_lock->unlock();
 807 
 808       // We now try to acquire the threads lock. Since this lock is hold by the VM thread during
 809       // the entire safepoint, the threads will all line up here during the safepoint.
 810       Threads_lock->lock_without_safepoint_check();
 811       // restore original state. This is important if the thread comes from compiled code, so it
 812       // will continue to execute with the _thread_in_Java state.
 813       thread->set_thread_state(state);
 814       Threads_lock->unlock();
 815       break;
 816 
 817     case _thread_in_native_trans:
 818     case _thread_blocked_trans:
 819     case _thread_new_trans:
 820       if (thread->safepoint_state()->type() == ThreadSafepointState::_call_back) {
 821         thread->print_thread_state();
 822         fatal("Deadlock in safepoint code.  "
 823               "Should have called back to the VM before blocking.");
 824       }
 825 
 826       // We transition the thread to state _thread_blocked here, but
 827       // we can't do our usual check for external suspension and then
 828       // self-suspend after the lock_without_safepoint_check() call
 829       // below because we are often called during transitions while
 830       // we hold different locks. That would leave us suspended while
 831       // holding a resource which results in deadlocks.
 832       thread->set_thread_state(_thread_blocked);
 833 
 834       // It is not safe to suspend a thread if we discover it is in _thread_in_native_trans. Hence,
 835       // the safepoint code might still be waiting for it to block. We need to change the state here,
 836       // so it can see that it is at a safepoint.
 837 
 838       // Block until the safepoint operation is completed.
 839       Threads_lock->lock_without_safepoint_check();
 840 
 841       // Restore state
 842       thread->set_thread_state(state);
 843 
 844       Threads_lock->unlock();
 845       break;
 846 
 847     default:
 848      fatal(err_msg("Illegal threadstate encountered: %d", state));
 849   }
 850 
 851   // Check for pending. async. exceptions or suspends - except if the
 852   // thread was blocked inside the VM. has_special_runtime_exit_condition()
 853   // is called last since it grabs a lock and we only want to do that when
 854   // we must.
 855   //
 856   // Note: we never deliver an async exception at a polling point as the
 857   // compiler may not have an exception handler for it. The polling
 858   // code will notice the async and deoptimize and the exception will
 859   // be delivered. (Polling at a return point is ok though). Sure is
 860   // a lot of bother for a deprecated feature...
 861   //
 862   // We don't deliver an async exception if the thread state is
 863   // _thread_in_native_trans so JNI functions won't be called with
 864   // a surprising pending exception. If the thread state is going back to java,
 865   // async exception is checked in check_special_condition_for_native_trans().
 866 
 867   if (state != _thread_blocked_trans &&
 868       state != _thread_in_vm_trans &&
 869       thread->has_special_runtime_exit_condition()) {
 870     thread->handle_special_runtime_exit_condition(
 871       !thread->is_at_poll_safepoint() && (state != _thread_in_native_trans));
 872   }
 873 }
 874 
 875 // ------------------------------------------------------------------------------------------------------
 876 // Exception handlers
 877 
 878 
 879 void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
 880   assert(thread->is_Java_thread(), "polling reference encountered by VM thread");
 881   assert(thread->thread_state() == _thread_in_Java, "should come from Java code");
 882   assert(SafepointSynchronize::is_synchronizing(), "polling encountered outside safepoint synchronization");
 883 
 884   if (ShowSafepointMsgs) {
 885     tty->print("handle_polling_page_exception: ");
 886   }
 887 
 888   if (PrintSafepointStatistics) {
 889     inc_page_trap_count();
 890   }
 891 
 892   ThreadSafepointState* state = thread->safepoint_state();
 893 
 894   state->handle_polling_page_exception();
 895 }
 896 
 897 
 898 void SafepointSynchronize::print_safepoint_timeout(SafepointTimeoutReason reason) {
 899   if (!timeout_error_printed) {
 900     timeout_error_printed = true;
 901     // Print out the thread infor which didn't reach the safepoint for debugging
 902     // purposes (useful when there are lots of threads in the debugger).
 903     tty->cr();
 904     tty->print_cr("# SafepointSynchronize::begin: Timeout detected:");
 905     if (reason ==  _spinning_timeout) {
 906       tty->print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint.");
 907     } else if (reason == _blocking_timeout) {
 908       tty->print_cr("# SafepointSynchronize::begin: Timed out while waiting for threads to stop.");
 909     }
 910 
 911     tty->print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:");
 912     ThreadSafepointState *cur_state;
 913     ResourceMark rm;
 914     for(JavaThread *cur_thread = Threads::first(); cur_thread;
 915         cur_thread = cur_thread->next()) {
 916       cur_state = cur_thread->safepoint_state();
 917 
 918       if (cur_thread->thread_state() != _thread_blocked &&
 919           ((reason == _spinning_timeout && cur_state->is_running()) ||
 920            (reason == _blocking_timeout && !cur_state->has_called_back()))) {
 921         tty->print("# ");
 922         cur_thread->print();
 923         tty->cr();
 924       }
 925     }
 926     tty->print_cr("# SafepointSynchronize::begin: (End of list)");
 927   }
 928 
 929   // To debug the long safepoint, specify both AbortVMOnSafepointTimeout &
 930   // ShowMessageBoxOnError.
 931   if (AbortVMOnSafepointTimeout) {
 932     char msg[1024];
 933     VM_Operation *op = VMThread::vm_operation();
 934     sprintf(msg, "Safepoint sync time longer than " INTX_FORMAT "ms detected when executing %s.",
 935             SafepointTimeoutDelay,
 936             op != NULL ? op->name() : "no vm operation");
 937     fatal(msg);
 938   }
 939 }
 940 
 941 
 942 // -------------------------------------------------------------------------------------------------------
 943 // Implementation of ThreadSafepointState
 944 
 945 ThreadSafepointState::ThreadSafepointState(JavaThread *thread) {
 946   _thread = thread;
 947   _type   = _running;
 948   _has_called_back = false;
 949   _at_poll_safepoint = false;
 950 }
 951 
 952 void ThreadSafepointState::create(JavaThread *thread) {
 953   ThreadSafepointState *state = new ThreadSafepointState(thread);
 954   thread->set_safepoint_state(state);
 955 }
 956 
 957 void ThreadSafepointState::destroy(JavaThread *thread) {
 958   if (thread->safepoint_state()) {
 959     delete(thread->safepoint_state());
 960     thread->set_safepoint_state(NULL);
 961   }
 962 }
 963 
 964 void ThreadSafepointState::examine_state_of_thread() {
 965   assert(is_running(), "better be running or just have hit safepoint poll");
 966 
 967   JavaThreadState state = _thread->thread_state();
 968 
 969   // Save the state at the start of safepoint processing.
 970   _orig_thread_state = state;
 971 
 972   // Check for a thread that is suspended. Note that thread resume tries
 973   // to grab the Threads_lock which we own here, so a thread cannot be
 974   // resumed during safepoint synchronization.
 975 
 976   // We check to see if this thread is suspended without locking to
 977   // avoid deadlocking with a third thread that is waiting for this
 978   // thread to be suspended. The third thread can notice the safepoint
 979   // that we're trying to start at the beginning of its SR_lock->wait()
 980   // call. If that happens, then the third thread will block on the
 981   // safepoint while still holding the underlying SR_lock. We won't be
 982   // able to get the SR_lock and we'll deadlock.
 983   //
 984   // We don't need to grab the SR_lock here for two reasons:
 985   // 1) The suspend flags are both volatile and are set with an
 986   //    Atomic::cmpxchg() call so we should see the suspended
 987   //    state right away.
 988   // 2) We're being called from the safepoint polling loop; if
 989   //    we don't see the suspended state on this iteration, then
 990   //    we'll come around again.
 991   //
 992   bool is_suspended = _thread->is_ext_suspended();
 993   if (is_suspended) {
 994     roll_forward(_at_safepoint);
 995     return;
 996   }
 997 
 998   // Some JavaThread states have an initial safepoint state of
 999   // running, but are actually at a safepoint. We will happily
1000   // agree and update the safepoint state here.
1001   if (SafepointSynchronize::safepoint_safe(_thread, state)) {
1002     SafepointSynchronize::check_for_lazy_critical_native(_thread, state);
1003     roll_forward(_at_safepoint);
1004     return;
1005   }
1006 
1007   if (state == _thread_in_vm) {
1008     roll_forward(_call_back);
1009     return;
1010   }
1011 
1012   // All other thread states will continue to run until they
1013   // transition and self-block in state _blocked
1014   // Safepoint polling in compiled code causes the Java threads to do the same.
1015   // Note: new threads may require a malloc so they must be allowed to finish
1016 
1017   assert(is_running(), "examine_state_of_thread on non-running thread");
1018   return;
1019 }
1020 
1021 // Returns true is thread could not be rolled forward at present position.
1022 void ThreadSafepointState::roll_forward(suspend_type type) {
1023   _type = type;
1024 
1025   switch(_type) {
1026     case _at_safepoint:
1027       SafepointSynchronize::signal_thread_at_safepoint();
1028       DEBUG_ONLY(_thread->set_visited_for_critical_count(true));
1029       if (_thread->in_critical()) {
1030         // Notice that this thread is in a critical section
1031         SafepointSynchronize::increment_jni_active_count();
1032       }
1033       break;
1034 
1035     case _call_back:
1036       set_has_called_back(false);
1037       break;
1038 
1039     case _running:
1040     default:
1041       ShouldNotReachHere();
1042   }
1043 }
1044 
1045 void ThreadSafepointState::restart() {
1046   switch(type()) {
1047     case _at_safepoint:
1048     case _call_back:
1049       break;
1050 
1051     case _running:
1052     default:
1053        tty->print_cr("restart thread " INTPTR_FORMAT " with state %d",
1054                       _thread, _type);
1055        _thread->print();
1056       ShouldNotReachHere();
1057   }
1058   _type = _running;
1059   set_has_called_back(false);
1060 }
1061 
1062 
1063 void ThreadSafepointState::print_on(outputStream *st) const {
1064   const char *s = NULL;
1065 
1066   switch(_type) {
1067     case _running                : s = "_running";              break;
1068     case _at_safepoint           : s = "_at_safepoint";         break;
1069     case _call_back              : s = "_call_back";            break;
1070     default:
1071       ShouldNotReachHere();
1072   }
1073 
1074   st->print_cr("Thread: " INTPTR_FORMAT
1075               "  [0x%2x] State: %s _has_called_back %d _at_poll_safepoint %d",
1076                _thread, _thread->osthread()->thread_id(), s, _has_called_back,
1077                _at_poll_safepoint);
1078 
1079   _thread->print_thread_state_on(st);
1080 }
1081 
1082 
1083 // ---------------------------------------------------------------------------------------------------------------------
1084 
1085 // Block the thread at the safepoint poll or poll return.
1086 void ThreadSafepointState::handle_polling_page_exception() {
1087 
1088   // Check state.  block() will set thread state to thread_in_vm which will
1089   // cause the safepoint state _type to become _call_back.
1090   assert(type() == ThreadSafepointState::_running,
1091          "polling page exception on thread not running state");
1092 
1093   // Step 1: Find the nmethod from the return address
1094   if (ShowSafepointMsgs && Verbose) {
1095     tty->print_cr("Polling page exception at " INTPTR_FORMAT, thread()->saved_exception_pc());
1096   }
1097   address real_return_addr = thread()->saved_exception_pc();
1098 
1099   CodeBlob *cb = CodeCache::find_blob(real_return_addr);
1100   assert(cb != NULL && cb->is_nmethod(), "return address should be in nmethod");
1101   nmethod* nm = (nmethod*)cb;
1102 
1103   // Find frame of caller
1104   frame stub_fr = thread()->last_frame();
1105   CodeBlob* stub_cb = stub_fr.cb();
1106   assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub");
1107   RegisterMap map(thread(), true);
1108   frame caller_fr = stub_fr.sender(&map);
1109 
1110   // Should only be poll_return or poll
1111   assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" );
1112 
1113   // This is a poll immediately before a return. The exception handling code
1114   // has already had the effect of causing the return to occur, so the execution
1115   // will continue immediately after the call. In addition, the oopmap at the
1116   // return point does not mark the return value as an oop (if it is), so
1117   // it needs a handle here to be updated.
1118   if( nm->is_at_poll_return(real_return_addr) ) {
1119     // See if return type is an oop.
1120     bool return_oop = nm->method()->is_returning_oop();
1121     Handle return_value;
1122     if (return_oop) {
1123       // The oop result has been saved on the stack together with all
1124       // the other registers. In order to preserve it over GCs we need
1125       // to keep it in a handle.
1126       oop result = caller_fr.saved_oop_result(&map);
1127       assert(result == NULL || result->is_oop(), "must be oop");
1128       return_value = Handle(thread(), result);
1129       assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
1130     }
1131 
1132     // Block the thread
1133     SafepointSynchronize::block(thread());
1134 
1135     // restore oop result, if any
1136     if (return_oop) {
1137       caller_fr.set_saved_oop_result(&map, return_value());
1138     }
1139   }
1140 
1141   // This is a safepoint poll. Verify the return address and block.
1142   else {
1143     set_at_poll_safepoint(true);
1144 
1145     // verify the blob built the "return address" correctly
1146     assert(real_return_addr == caller_fr.pc(), "must match");
1147 
1148     // Block the thread
1149     SafepointSynchronize::block(thread());
1150     set_at_poll_safepoint(false);
1151 
1152     // If we have a pending async exception deoptimize the frame
1153     // as otherwise we may never deliver it.
1154     if (thread()->has_async_condition()) {
1155       ThreadInVMfromJavaNoAsyncException __tiv(thread());
1156       Deoptimization::deoptimize_frame(thread(), caller_fr.id());
1157     }
1158 
1159     // If an exception has been installed we must check for a pending deoptimization
1160     // Deoptimize frame if exception has been thrown.
1161 
1162     if (thread()->has_pending_exception() ) {
1163       RegisterMap map(thread(), true);
1164       frame caller_fr = stub_fr.sender(&map);
1165       if (caller_fr.is_deoptimized_frame()) {
1166         // The exception patch will destroy registers that are still
1167         // live and will be needed during deoptimization. Defer the
1168         // Async exception should have defered the exception until the
1169         // next safepoint which will be detected when we get into
1170         // the interpreter so if we have an exception now things
1171         // are messed up.
1172 
1173         fatal("Exception installed and deoptimization is pending");
1174       }
1175     }
1176   }
1177 }
1178 
1179 
1180 //
1181 //                     Statistics & Instrumentations
1182 //
1183 SafepointSynchronize::SafepointStats*  SafepointSynchronize::_safepoint_stats = NULL;
1184 jlong  SafepointSynchronize::_safepoint_begin_time = 0;
1185 int    SafepointSynchronize::_cur_stat_index = 0;
1186 julong SafepointSynchronize::_safepoint_reasons[VM_Operation::VMOp_Terminating];
1187 julong SafepointSynchronize::_coalesced_vmop_count = 0;
1188 jlong  SafepointSynchronize::_max_sync_time = 0;
1189 jlong  SafepointSynchronize::_max_vmop_time = 0;
1190 float  SafepointSynchronize::_ts_of_current_safepoint = 0.0f;
1191 
1192 static jlong  cleanup_end_time = 0;
1193 static bool   need_to_track_page_armed_status = false;
1194 static bool   init_done = false;
1195 
1196 // Helper method to print the header.
1197 static void print_header() {
1198   tty->print("         vmop                    "
1199              "[threads: total initially_running wait_to_block]    ");
1200   tty->print("[time: spin block sync cleanup vmop] ");
1201 
1202   // no page armed status printed out if it is always armed.
1203   if (need_to_track_page_armed_status) {
1204     tty->print("page_armed ");
1205   }
1206 
1207   tty->print_cr("page_trap_count");
1208 }
1209 
1210 void SafepointSynchronize::deferred_initialize_stat() {
1211   if (init_done) return;
1212 
1213   if (PrintSafepointStatisticsCount <= 0) {
1214     fatal("Wrong PrintSafepointStatisticsCount");
1215   }
1216 
1217   // If PrintSafepointStatisticsTimeout is specified, the statistics data will
1218   // be printed right away, in which case, _safepoint_stats will regress to
1219   // a single element array. Otherwise, it is a circular ring buffer with default
1220   // size of PrintSafepointStatisticsCount.
1221   int stats_array_size;
1222   if (PrintSafepointStatisticsTimeout > 0) {
1223     stats_array_size = 1;
1224     PrintSafepointStatistics = true;
1225   } else {
1226     stats_array_size = PrintSafepointStatisticsCount;
1227   }
1228   _safepoint_stats = (SafepointStats*)os::malloc(stats_array_size
1229                                                  * sizeof(SafepointStats), mtInternal);
1230   guarantee(_safepoint_stats != NULL,
1231             "not enough memory for safepoint instrumentation data");
1232 
1233   if (UseCompilerSafepoints && DeferPollingPageLoopCount >= 0) {
1234     need_to_track_page_armed_status = true;
1235   }
1236   init_done = true;
1237 }
1238 
1239 void SafepointSynchronize::begin_statistics(int nof_threads, int nof_running) {
1240   assert(init_done, "safepoint statistics array hasn't been initialized");
1241   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1242 
1243   spstat->_time_stamp = _ts_of_current_safepoint;
1244 
1245   VM_Operation *op = VMThread::vm_operation();
1246   spstat->_vmop_type = (op != NULL ? op->type() : -1);
1247   if (op != NULL) {
1248     _safepoint_reasons[spstat->_vmop_type]++;
1249   }
1250 
1251   spstat->_nof_total_threads = nof_threads;
1252   spstat->_nof_initial_running_threads = nof_running;
1253   spstat->_nof_threads_hit_page_trap = 0;
1254 
1255   // Records the start time of spinning. The real time spent on spinning
1256   // will be adjusted when spin is done. Same trick is applied for time
1257   // spent on waiting for threads to block.
1258   if (nof_running != 0) {
1259     spstat->_time_to_spin = os::javaTimeNanos();
1260   }  else {
1261     spstat->_time_to_spin = 0;
1262   }
1263 }
1264 
1265 void SafepointSynchronize::update_statistics_on_spin_end() {
1266   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1267 
1268   jlong cur_time = os::javaTimeNanos();
1269 
1270   spstat->_nof_threads_wait_to_block = _waiting_to_block;
1271   if (spstat->_nof_initial_running_threads != 0) {
1272     spstat->_time_to_spin = cur_time - spstat->_time_to_spin;
1273   }
1274 
1275   if (need_to_track_page_armed_status) {
1276     spstat->_page_armed = (PageArmed == 1);
1277   }
1278 
1279   // Records the start time of waiting for to block. Updated when block is done.
1280   if (_waiting_to_block != 0) {
1281     spstat->_time_to_wait_to_block = cur_time;
1282   } else {
1283     spstat->_time_to_wait_to_block = 0;
1284   }
1285 }
1286 
1287 void SafepointSynchronize::update_statistics_on_sync_end(jlong end_time) {
1288   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1289 
1290   if (spstat->_nof_threads_wait_to_block != 0) {
1291     spstat->_time_to_wait_to_block = end_time -
1292       spstat->_time_to_wait_to_block;
1293   }
1294 
1295   // Records the end time of sync which will be used to calculate the total
1296   // vm operation time. Again, the real time spending in syncing will be deducted
1297   // from the start of the sync time later when end_statistics is called.
1298   spstat->_time_to_sync = end_time - _safepoint_begin_time;
1299   if (spstat->_time_to_sync > _max_sync_time) {
1300     _max_sync_time = spstat->_time_to_sync;
1301   }
1302 
1303   spstat->_time_to_do_cleanups = end_time;
1304 }
1305 
1306 void SafepointSynchronize::update_statistics_on_cleanup_end(jlong end_time) {
1307   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1308 
1309   // Record how long spent in cleanup tasks.
1310   spstat->_time_to_do_cleanups = end_time - spstat->_time_to_do_cleanups;
1311 
1312   cleanup_end_time = end_time;
1313 }
1314 
1315 void SafepointSynchronize::end_statistics(jlong vmop_end_time) {
1316   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1317 
1318   // Update the vm operation time.
1319   spstat->_time_to_exec_vmop = vmop_end_time -  cleanup_end_time;
1320   if (spstat->_time_to_exec_vmop > _max_vmop_time) {
1321     _max_vmop_time = spstat->_time_to_exec_vmop;
1322   }
1323   // Only the sync time longer than the specified
1324   // PrintSafepointStatisticsTimeout will be printed out right away.
1325   // By default, it is -1 meaning all samples will be put into the list.
1326   if ( PrintSafepointStatisticsTimeout > 0) {
1327     if (spstat->_time_to_sync > PrintSafepointStatisticsTimeout * MICROUNITS) {
1328       print_statistics();
1329     }
1330   } else {
1331     // The safepoint statistics will be printed out when the _safepoin_stats
1332     // array fills up.
1333     if (_cur_stat_index == PrintSafepointStatisticsCount - 1) {
1334       print_statistics();
1335       _cur_stat_index = 0;
1336     } else {
1337       _cur_stat_index++;
1338     }
1339   }
1340 }
1341 
1342 void SafepointSynchronize::print_statistics() {
1343   SafepointStats* sstats = _safepoint_stats;
1344 
1345   for (int index = 0; index <= _cur_stat_index; index++) {
1346     if (index % 30 == 0) {
1347       print_header();
1348     }
1349     sstats = &_safepoint_stats[index];
1350     tty->print("%.3f: ", sstats->_time_stamp);
1351     tty->print("%-26s       ["
1352                INT32_FORMAT_W(8) INT32_FORMAT_W(11) INT32_FORMAT_W(15)
1353                "    ]    ",
1354                sstats->_vmop_type == -1 ? "no vm operation" :
1355                VM_Operation::name(sstats->_vmop_type),
1356                sstats->_nof_total_threads,
1357                sstats->_nof_initial_running_threads,
1358                sstats->_nof_threads_wait_to_block);
1359     // "/ MICROUNITS " is to convert the unit from nanos to millis.
1360     tty->print("  ["
1361                INT64_FORMAT_W(6) INT64_FORMAT_W(6)
1362                INT64_FORMAT_W(6) INT64_FORMAT_W(6)
1363                INT64_FORMAT_W(6) "    ]  ",
1364                sstats->_time_to_spin / MICROUNITS,
1365                sstats->_time_to_wait_to_block / MICROUNITS,
1366                sstats->_time_to_sync / MICROUNITS,
1367                sstats->_time_to_do_cleanups / MICROUNITS,
1368                sstats->_time_to_exec_vmop / MICROUNITS);
1369 
1370     if (need_to_track_page_armed_status) {
1371       tty->print(INT32_FORMAT "         ", sstats->_page_armed);
1372     }
1373     tty->print_cr(INT32_FORMAT "   ", sstats->_nof_threads_hit_page_trap);
1374   }
1375 }
1376 
1377 // This method will be called when VM exits. It will first call
1378 // print_statistics to print out the rest of the sampling.  Then
1379 // it tries to summarize the sampling.
1380 void SafepointSynchronize::print_stat_on_exit() {
1381   if (_safepoint_stats == NULL) return;
1382 
1383   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1384 
1385   // During VM exit, end_statistics may not get called and in that
1386   // case, if the sync time is less than PrintSafepointStatisticsTimeout,
1387   // don't print it out.
1388   // Approximate the vm op time.
1389   _safepoint_stats[_cur_stat_index]._time_to_exec_vmop =
1390     os::javaTimeNanos() - cleanup_end_time;
1391 
1392   if ( PrintSafepointStatisticsTimeout < 0 ||
1393        spstat->_time_to_sync > PrintSafepointStatisticsTimeout * MICROUNITS) {
1394     print_statistics();
1395   }
1396   tty->cr();
1397 
1398   // Print out polling page sampling status.
1399   if (!need_to_track_page_armed_status) {
1400     if (UseCompilerSafepoints) {
1401       tty->print_cr("Polling page always armed");
1402     }
1403   } else {
1404     tty->print_cr("Defer polling page loop count = %d\n",
1405                  DeferPollingPageLoopCount);
1406   }
1407 
1408   for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) {
1409     if (_safepoint_reasons[index] != 0) {
1410       tty->print_cr("%-26s" UINT64_FORMAT_W(10), VM_Operation::name(index),
1411                     _safepoint_reasons[index]);
1412     }
1413   }
1414 
1415   tty->print_cr(UINT64_FORMAT_W(5) " VM operations coalesced during safepoint",
1416                 _coalesced_vmop_count);
1417   tty->print_cr("Maximum sync time  " INT64_FORMAT_W(5) " ms",
1418                 _max_sync_time / MICROUNITS);
1419   tty->print_cr("Maximum vm operation time (except for Exit VM operation)  "
1420                 INT64_FORMAT_W(5) " ms",
1421                 _max_vmop_time / MICROUNITS);
1422 }
1423 
1424 // ------------------------------------------------------------------------------------------------
1425 // Non-product code
1426 
1427 #ifndef PRODUCT
1428 
1429 void SafepointSynchronize::print_state() {
1430   if (_state == _not_synchronized) {
1431     tty->print_cr("not synchronized");
1432   } else if (_state == _synchronizing || _state == _synchronized) {
1433     tty->print_cr("State: %s", (_state == _synchronizing) ? "synchronizing" :
1434                   "synchronized");
1435 
1436     for(JavaThread *cur = Threads::first(); cur; cur = cur->next()) {
1437        cur->safepoint_state()->print();
1438     }
1439   }
1440 }
1441 
1442 void SafepointSynchronize::safepoint_msg(const char* format, ...) {
1443   if (ShowSafepointMsgs) {
1444     va_list ap;
1445     va_start(ap, format);
1446     tty->vprint_cr(format, ap);
1447     va_end(ap);
1448   }
1449 }
1450 
1451 #endif // !PRODUCT