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