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     HandleMark hm(thread());
1122     Handle return_value;
1123     if (return_oop) {
1124       // The oop result has been saved on the stack together with all
1125       // the other registers. In order to preserve it over GCs we need
1126       // to keep it in a handle.
1127       oop result = caller_fr.saved_oop_result(&map);
1128       assert(result == NULL || result->is_oop(), "must be oop");
1129       return_value = Handle(thread(), result);
1130       assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
1131     }
1132 
1133     // Block the thread
1134     SafepointSynchronize::block(thread());
1135 
1136     // restore oop result, if any
1137     if (return_oop) {
1138       caller_fr.set_saved_oop_result(&map, return_value());
1139     }
1140   }
1141 
1142   // This is a safepoint poll. Verify the return address and block.
1143   else {
1144     set_at_poll_safepoint(true);
1145 
1146     // verify the blob built the "return address" correctly
1147     assert(real_return_addr == caller_fr.pc(), "must match");
1148 
1149     // Block the thread
1150     SafepointSynchronize::block(thread());
1151     set_at_poll_safepoint(false);
1152 
1153     // If we have a pending async exception deoptimize the frame
1154     // as otherwise we may never deliver it.
1155     if (thread()->has_async_condition()) {
1156       ThreadInVMfromJavaNoAsyncException __tiv(thread());
1157       Deoptimization::deoptimize_frame(thread(), caller_fr.id());
1158     }
1159 
1160     // If an exception has been installed we must check for a pending deoptimization
1161     // Deoptimize frame if exception has been thrown.
1162 
1163     if (thread()->has_pending_exception() ) {
1164       RegisterMap map(thread(), true);
1165       frame caller_fr = stub_fr.sender(&map);
1166       if (caller_fr.is_deoptimized_frame()) {
1167         // The exception patch will destroy registers that are still
1168         // live and will be needed during deoptimization. Defer the
1169         // Async exception should have defered the exception until the
1170         // next safepoint which will be detected when we get into
1171         // the interpreter so if we have an exception now things
1172         // are messed up.
1173 
1174         fatal("Exception installed and deoptimization is pending");
1175       }
1176     }
1177   }
1178 }
1179 
1180 
1181 //
1182 //                     Statistics & Instrumentations
1183 //
1184 SafepointSynchronize::SafepointStats*  SafepointSynchronize::_safepoint_stats = NULL;
1185 jlong  SafepointSynchronize::_safepoint_begin_time = 0;
1186 int    SafepointSynchronize::_cur_stat_index = 0;
1187 julong SafepointSynchronize::_safepoint_reasons[VM_Operation::VMOp_Terminating];
1188 julong SafepointSynchronize::_coalesced_vmop_count = 0;
1189 jlong  SafepointSynchronize::_max_sync_time = 0;
1190 jlong  SafepointSynchronize::_max_vmop_time = 0;
1191 float  SafepointSynchronize::_ts_of_current_safepoint = 0.0f;
1192 
1193 static jlong  cleanup_end_time = 0;
1194 static bool   need_to_track_page_armed_status = false;
1195 static bool   init_done = false;
1196 
1197 // Helper method to print the header.
1198 static void print_header() {
1199   tty->print("         vmop                    "
1200              "[threads: total initially_running wait_to_block]    ");
1201   tty->print("[time: spin block sync cleanup vmop] ");
1202 
1203   // no page armed status printed out if it is always armed.
1204   if (need_to_track_page_armed_status) {
1205     tty->print("page_armed ");
1206   }
1207 
1208   tty->print_cr("page_trap_count");
1209 }
1210 
1211 void SafepointSynchronize::deferred_initialize_stat() {
1212   if (init_done) return;
1213 
1214   if (PrintSafepointStatisticsCount <= 0) {
1215     fatal("Wrong PrintSafepointStatisticsCount");
1216   }
1217 
1218   // If PrintSafepointStatisticsTimeout is specified, the statistics data will
1219   // be printed right away, in which case, _safepoint_stats will regress to
1220   // a single element array. Otherwise, it is a circular ring buffer with default
1221   // size of PrintSafepointStatisticsCount.
1222   int stats_array_size;
1223   if (PrintSafepointStatisticsTimeout > 0) {
1224     stats_array_size = 1;
1225     PrintSafepointStatistics = true;
1226   } else {
1227     stats_array_size = PrintSafepointStatisticsCount;
1228   }
1229   _safepoint_stats = (SafepointStats*)os::malloc(stats_array_size
1230                                                  * sizeof(SafepointStats), mtInternal);
1231   guarantee(_safepoint_stats != NULL,
1232             "not enough memory for safepoint instrumentation data");
1233 
1234   if (UseCompilerSafepoints && DeferPollingPageLoopCount >= 0) {
1235     need_to_track_page_armed_status = true;
1236   }
1237   init_done = true;
1238 }
1239 
1240 void SafepointSynchronize::begin_statistics(int nof_threads, int nof_running) {
1241   assert(init_done, "safepoint statistics array hasn't been initialized");
1242   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1243 
1244   spstat->_time_stamp = _ts_of_current_safepoint;
1245 
1246   VM_Operation *op = VMThread::vm_operation();
1247   spstat->_vmop_type = (op != NULL ? op->type() : -1);
1248   if (op != NULL) {
1249     _safepoint_reasons[spstat->_vmop_type]++;
1250   }
1251 
1252   spstat->_nof_total_threads = nof_threads;
1253   spstat->_nof_initial_running_threads = nof_running;
1254   spstat->_nof_threads_hit_page_trap = 0;
1255 
1256   // Records the start time of spinning. The real time spent on spinning
1257   // will be adjusted when spin is done. Same trick is applied for time
1258   // spent on waiting for threads to block.
1259   if (nof_running != 0) {
1260     spstat->_time_to_spin = os::javaTimeNanos();
1261   }  else {
1262     spstat->_time_to_spin = 0;
1263   }
1264 }
1265 
1266 void SafepointSynchronize::update_statistics_on_spin_end() {
1267   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1268 
1269   jlong cur_time = os::javaTimeNanos();
1270 
1271   spstat->_nof_threads_wait_to_block = _waiting_to_block;
1272   if (spstat->_nof_initial_running_threads != 0) {
1273     spstat->_time_to_spin = cur_time - spstat->_time_to_spin;
1274   }
1275 
1276   if (need_to_track_page_armed_status) {
1277     spstat->_page_armed = (PageArmed == 1);
1278   }
1279 
1280   // Records the start time of waiting for to block. Updated when block is done.
1281   if (_waiting_to_block != 0) {
1282     spstat->_time_to_wait_to_block = cur_time;
1283   } else {
1284     spstat->_time_to_wait_to_block = 0;
1285   }
1286 }
1287 
1288 void SafepointSynchronize::update_statistics_on_sync_end(jlong end_time) {
1289   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1290 
1291   if (spstat->_nof_threads_wait_to_block != 0) {
1292     spstat->_time_to_wait_to_block = end_time -
1293       spstat->_time_to_wait_to_block;
1294   }
1295 
1296   // Records the end time of sync which will be used to calculate the total
1297   // vm operation time. Again, the real time spending in syncing will be deducted
1298   // from the start of the sync time later when end_statistics is called.
1299   spstat->_time_to_sync = end_time - _safepoint_begin_time;
1300   if (spstat->_time_to_sync > _max_sync_time) {
1301     _max_sync_time = spstat->_time_to_sync;
1302   }
1303 
1304   spstat->_time_to_do_cleanups = end_time;
1305 }
1306 
1307 void SafepointSynchronize::update_statistics_on_cleanup_end(jlong end_time) {
1308   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1309 
1310   // Record how long spent in cleanup tasks.
1311   spstat->_time_to_do_cleanups = end_time - spstat->_time_to_do_cleanups;
1312 
1313   cleanup_end_time = end_time;
1314 }
1315 
1316 void SafepointSynchronize::end_statistics(jlong vmop_end_time) {
1317   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1318 
1319   // Update the vm operation time.
1320   spstat->_time_to_exec_vmop = vmop_end_time -  cleanup_end_time;
1321   if (spstat->_time_to_exec_vmop > _max_vmop_time) {
1322     _max_vmop_time = spstat->_time_to_exec_vmop;
1323   }
1324   // Only the sync time longer than the specified
1325   // PrintSafepointStatisticsTimeout will be printed out right away.
1326   // By default, it is -1 meaning all samples will be put into the list.
1327   if ( PrintSafepointStatisticsTimeout > 0) {
1328     if (spstat->_time_to_sync > PrintSafepointStatisticsTimeout * MICROUNITS) {
1329       print_statistics();
1330     }
1331   } else {
1332     // The safepoint statistics will be printed out when the _safepoin_stats
1333     // array fills up.
1334     if (_cur_stat_index == PrintSafepointStatisticsCount - 1) {
1335       print_statistics();
1336       _cur_stat_index = 0;
1337     } else {
1338       _cur_stat_index++;
1339     }
1340   }
1341 }
1342 
1343 void SafepointSynchronize::print_statistics() {
1344   SafepointStats* sstats = _safepoint_stats;
1345 
1346   for (int index = 0; index <= _cur_stat_index; index++) {
1347     if (index % 30 == 0) {
1348       print_header();
1349     }
1350     sstats = &_safepoint_stats[index];
1351     tty->print("%.3f: ", sstats->_time_stamp);
1352     tty->print("%-26s       ["
1353                INT32_FORMAT_W(8) INT32_FORMAT_W(11) INT32_FORMAT_W(15)
1354                "    ]    ",
1355                sstats->_vmop_type == -1 ? "no vm operation" :
1356                VM_Operation::name(sstats->_vmop_type),
1357                sstats->_nof_total_threads,
1358                sstats->_nof_initial_running_threads,
1359                sstats->_nof_threads_wait_to_block);
1360     // "/ MICROUNITS " is to convert the unit from nanos to millis.
1361     tty->print("  ["
1362                INT64_FORMAT_W(6) INT64_FORMAT_W(6)
1363                INT64_FORMAT_W(6) INT64_FORMAT_W(6)
1364                INT64_FORMAT_W(6) "    ]  ",
1365                sstats->_time_to_spin / MICROUNITS,
1366                sstats->_time_to_wait_to_block / MICROUNITS,
1367                sstats->_time_to_sync / MICROUNITS,
1368                sstats->_time_to_do_cleanups / MICROUNITS,
1369                sstats->_time_to_exec_vmop / MICROUNITS);
1370 
1371     if (need_to_track_page_armed_status) {
1372       tty->print(INT32_FORMAT "         ", sstats->_page_armed);
1373     }
1374     tty->print_cr(INT32_FORMAT "   ", sstats->_nof_threads_hit_page_trap);
1375   }
1376 }
1377 
1378 // This method will be called when VM exits. It will first call
1379 // print_statistics to print out the rest of the sampling.  Then
1380 // it tries to summarize the sampling.
1381 void SafepointSynchronize::print_stat_on_exit() {
1382   if (_safepoint_stats == NULL) return;
1383 
1384   SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1385 
1386   // During VM exit, end_statistics may not get called and in that
1387   // case, if the sync time is less than PrintSafepointStatisticsTimeout,
1388   // don't print it out.
1389   // Approximate the vm op time.
1390   _safepoint_stats[_cur_stat_index]._time_to_exec_vmop =
1391     os::javaTimeNanos() - cleanup_end_time;
1392 
1393   if ( PrintSafepointStatisticsTimeout < 0 ||
1394        spstat->_time_to_sync > PrintSafepointStatisticsTimeout * MICROUNITS) {
1395     print_statistics();
1396   }
1397   tty->cr();
1398 
1399   // Print out polling page sampling status.
1400   if (!need_to_track_page_armed_status) {
1401     if (UseCompilerSafepoints) {
1402       tty->print_cr("Polling page always armed");
1403     }
1404   } else {
1405     tty->print_cr("Defer polling page loop count = %d\n",
1406                  DeferPollingPageLoopCount);
1407   }
1408 
1409   for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) {
1410     if (_safepoint_reasons[index] != 0) {
1411       tty->print_cr("%-26s" UINT64_FORMAT_W(10), VM_Operation::name(index),
1412                     _safepoint_reasons[index]);
1413     }
1414   }
1415 
1416   tty->print_cr(UINT64_FORMAT_W(5) " VM operations coalesced during safepoint",
1417                 _coalesced_vmop_count);
1418   tty->print_cr("Maximum sync time  " INT64_FORMAT_W(5) " ms",
1419                 _max_sync_time / MICROUNITS);
1420   tty->print_cr("Maximum vm operation time (except for Exit VM operation)  "
1421                 INT64_FORMAT_W(5) " ms",
1422                 _max_vmop_time / MICROUNITS);
1423 }
1424 
1425 // ------------------------------------------------------------------------------------------------
1426 // Non-product code
1427 
1428 #ifndef PRODUCT
1429 
1430 void SafepointSynchronize::print_state() {
1431   if (_state == _not_synchronized) {
1432     tty->print_cr("not synchronized");
1433   } else if (_state == _synchronizing || _state == _synchronized) {
1434     tty->print_cr("State: %s", (_state == _synchronizing) ? "synchronizing" :
1435                   "synchronized");
1436 
1437     for(JavaThread *cur = Threads::first(); cur; cur = cur->next()) {
1438        cur->safepoint_state()->print();
1439     }
1440   }
1441 }
1442 
1443 void SafepointSynchronize::safepoint_msg(const char* format, ...) {
1444   if (ShowSafepointMsgs) {
1445     va_list ap;
1446     va_start(ap, format);
1447     tty->vprint_cr(format, ap);
1448     va_end(ap);
1449   }
1450 }
1451 
1452 #endif // !PRODUCT