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