1 /*
   2  * Copyright (c) 1997, 2020, 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/classLoaderDataGraph.inline.hpp"
  27 #include "classfile/dictionary.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/icBuffer.hpp"
  33 #include "code/nmethod.hpp"
  34 #include "code/pcDesc.hpp"
  35 #include "code/scopeDesc.hpp"
  36 #include "compiler/compilationPolicy.hpp"
  37 #include "gc/shared/collectedHeap.hpp"
  38 #include "gc/shared/gcLocker.hpp"
  39 #include "gc/shared/oopStorage.hpp"
  40 #include "gc/shared/strongRootsScope.hpp"
  41 #include "gc/shared/workgroup.hpp"
  42 #include "interpreter/interpreter.hpp"
  43 #include "jfr/jfrEvents.hpp"
  44 #include "logging/log.hpp"
  45 #include "logging/logStream.hpp"
  46 #include "memory/resourceArea.hpp"
  47 #include "memory/universe.hpp"
  48 #include "oops/oop.inline.hpp"
  49 #include "oops/symbol.hpp"
  50 #include "runtime/atomic.hpp"
  51 #include "runtime/deoptimization.hpp"
  52 #include "runtime/frame.inline.hpp"
  53 #include "runtime/handles.inline.hpp"
  54 #include "runtime/interfaceSupport.inline.hpp"
  55 #include "runtime/mutexLocker.hpp"
  56 #include "runtime/orderAccess.hpp"
  57 #include "runtime/osThread.hpp"
  58 #include "runtime/safepoint.hpp"
  59 #include "runtime/safepointMechanism.inline.hpp"
  60 #include "runtime/signature.hpp"
  61 #include "runtime/stubCodeGenerator.hpp"
  62 #include "runtime/stubRoutines.hpp"
  63 #include "runtime/sweeper.hpp"
  64 #include "runtime/synchronizer.hpp"
  65 #include "runtime/thread.inline.hpp"
  66 #include "runtime/threadSMR.hpp"
  67 #include "runtime/timerTrace.hpp"
  68 #include "services/runtimeService.hpp"
  69 #include "utilities/events.hpp"
  70 #include "utilities/macros.hpp"
  71 
  72 static void post_safepoint_begin_event(EventSafepointBegin& event,
  73                                        uint64_t safepoint_id,
  74                                        int thread_count,
  75                                        int critical_thread_count) {
  76   if (event.should_commit()) {
  77     event.set_safepointId(safepoint_id);
  78     event.set_totalThreadCount(thread_count);
  79     event.set_jniCriticalThreadCount(critical_thread_count);
  80     event.commit();
  81   }
  82 }
  83 
  84 static void post_safepoint_cleanup_event(EventSafepointCleanup& event, uint64_t safepoint_id) {
  85   if (event.should_commit()) {
  86     event.set_safepointId(safepoint_id);
  87     event.commit();
  88   }
  89 }
  90 
  91 static void post_safepoint_synchronize_event(EventSafepointStateSynchronization& event,
  92                                              uint64_t safepoint_id,
  93                                              int initial_number_of_threads,
  94                                              int threads_waiting_to_block,
  95                                              uint64_t iterations) {
  96   if (event.should_commit()) {
  97     event.set_safepointId(safepoint_id);
  98     event.set_initialThreadCount(initial_number_of_threads);
  99     event.set_runningThreadCount(threads_waiting_to_block);
 100     event.set_iterations(iterations);
 101     event.commit();
 102   }
 103 }
 104 
 105 static void post_safepoint_cleanup_task_event(EventSafepointCleanupTask& event,
 106                                               uint64_t safepoint_id,
 107                                               const char* name) {
 108   if (event.should_commit()) {
 109     event.set_safepointId(safepoint_id);
 110     event.set_name(name);
 111     event.commit();
 112   }
 113 }
 114 
 115 static void post_safepoint_end_event(EventSafepointEnd& event, uint64_t safepoint_id) {
 116   if (event.should_commit()) {
 117     event.set_safepointId(safepoint_id);
 118     event.commit();
 119   }
 120 }
 121 
 122 // SafepointCheck
 123 SafepointStateTracker::SafepointStateTracker(uint64_t safepoint_id, bool at_safepoint)
 124   : _safepoint_id(safepoint_id), _at_safepoint(at_safepoint) {}
 125 
 126 bool SafepointStateTracker::safepoint_state_changed() {
 127   return _safepoint_id != SafepointSynchronize::safepoint_id() ||
 128     _at_safepoint != SafepointSynchronize::is_at_safepoint();
 129 }
 130 
 131 // --------------------------------------------------------------------------------------------------
 132 // Implementation of Safepoint begin/end
 133 
 134 SafepointSynchronize::SynchronizeState volatile SafepointSynchronize::_state = SafepointSynchronize::_not_synchronized;
 135 int SafepointSynchronize::_waiting_to_block = 0;
 136 volatile uint64_t SafepointSynchronize::_safepoint_counter = 0;
 137 uint64_t SafepointSynchronize::_safepoint_id = 0;
 138 const uint64_t SafepointSynchronize::InactiveSafepointCounter = 0;
 139 int SafepointSynchronize::_current_jni_active_count = 0;
 140 
 141 WaitBarrier* SafepointSynchronize::_wait_barrier;
 142 
 143 static bool timeout_error_printed = false;
 144 
 145 // Statistic related
 146 static jlong _safepoint_begin_time = 0;
 147 static volatile int _nof_threads_hit_polling_page = 0;
 148 
 149 void SafepointSynchronize::init(Thread* vmthread) {
 150   // WaitBarrier should never be destroyed since we will have
 151   // threads waiting on it while exiting.
 152   _wait_barrier = new WaitBarrier(vmthread);
 153   SafepointTracing::init();
 154 }
 155 
 156 void SafepointSynchronize::increment_jni_active_count() {
 157   assert(Thread::current()->is_VM_thread(), "Only VM thread may increment");
 158   ++_current_jni_active_count;
 159 }
 160 
 161 void SafepointSynchronize::decrement_waiting_to_block() {
 162   assert(_waiting_to_block > 0, "sanity check");
 163   assert(Thread::current()->is_VM_thread(), "Only VM thread may decrement");
 164   --_waiting_to_block;
 165 }
 166 
 167 bool SafepointSynchronize::thread_not_running(ThreadSafepointState *cur_state) {
 168   if (!cur_state->is_running()) {
 169     return true;
 170   }
 171   cur_state->examine_state_of_thread(SafepointSynchronize::safepoint_counter());
 172   if (!cur_state->is_running()) {
 173     return true;
 174   }
 175   LogTarget(Trace, safepoint) lt;
 176   if (lt.is_enabled()) {
 177     ResourceMark rm;
 178     LogStream ls(lt);
 179     cur_state->print_on(&ls);
 180   }
 181   return false;
 182 }
 183 
 184 #ifdef ASSERT
 185 static void assert_list_is_valid(const ThreadSafepointState* tss_head, int still_running) {
 186   int a = 0;
 187   const ThreadSafepointState *tmp_tss = tss_head;
 188   while (tmp_tss != NULL) {
 189     ++a;
 190     assert(tmp_tss->is_running(), "Illegal initial state");
 191     tmp_tss = tmp_tss->get_next();
 192   }
 193   assert(a == still_running, "Must be the same");
 194 }
 195 #endif // ASSERT
 196 
 197 static void back_off(int64_t start_time) {
 198   // We start with fine-grained nanosleeping until a millisecond has
 199   // passed, at which point we resort to plain naked_short_sleep.
 200   if (os::javaTimeNanos() - start_time < NANOSECS_PER_MILLISEC) {
 201     os::naked_short_nanosleep(10 * (NANOUNITS / MICROUNITS));
 202   } else {
 203     os::naked_short_sleep(1);
 204   }
 205 }
 206 
 207 int SafepointSynchronize::synchronize_threads(jlong safepoint_limit_time, int nof_threads, int* initial_running)
 208 {
 209   JavaThreadIteratorWithHandle jtiwh;
 210 
 211 #ifdef ASSERT
 212   for (; JavaThread *cur = jtiwh.next(); ) {
 213     assert(cur->safepoint_state()->is_running(), "Illegal initial state");
 214   }
 215   jtiwh.rewind();
 216 #endif // ASSERT
 217 
 218   // Iterate through all threads until it has been determined how to stop them all at a safepoint.
 219   int still_running = nof_threads;
 220   ThreadSafepointState *tss_head = NULL;
 221   ThreadSafepointState **p_prev = &tss_head;
 222   for (; JavaThread *cur = jtiwh.next(); ) {
 223     ThreadSafepointState *cur_tss = cur->safepoint_state();
 224     assert(cur_tss->get_next() == NULL, "Must be NULL");
 225     if (thread_not_running(cur_tss)) {
 226       --still_running;
 227     } else {
 228       *p_prev = cur_tss;
 229       p_prev = cur_tss->next_ptr();
 230     }
 231   }
 232   *p_prev = NULL;
 233 
 234   DEBUG_ONLY(assert_list_is_valid(tss_head, still_running);)
 235 
 236   *initial_running = still_running;
 237 
 238   // If there is no thread still running, we are already done.
 239   if (still_running <= 0) {
 240     assert(tss_head == NULL, "Must be empty");
 241     return 1;
 242   }
 243 
 244   int iterations = 1; // The first iteration is above.
 245   int64_t start_time = os::javaTimeNanos();
 246 
 247   do {
 248     // Check if this has taken too long:
 249     if (SafepointTimeout && safepoint_limit_time < os::javaTimeNanos()) {
 250       print_safepoint_timeout();
 251     }
 252 
 253     p_prev = &tss_head;
 254     ThreadSafepointState *cur_tss = tss_head;
 255     while (cur_tss != NULL) {
 256       assert(cur_tss->is_running(), "Illegal initial state");
 257       if (thread_not_running(cur_tss)) {
 258         --still_running;
 259         *p_prev = NULL;
 260         ThreadSafepointState *tmp = cur_tss;
 261         cur_tss = cur_tss->get_next();
 262         tmp->set_next(NULL);
 263       } else {
 264         *p_prev = cur_tss;
 265         p_prev = cur_tss->next_ptr();
 266         cur_tss = cur_tss->get_next();
 267       }
 268     }
 269 
 270     DEBUG_ONLY(assert_list_is_valid(tss_head, still_running);)
 271 
 272     if (still_running > 0) {
 273       back_off(start_time);
 274     }
 275 
 276     iterations++;
 277   } while (still_running > 0);
 278 
 279   assert(tss_head == NULL, "Must be empty");
 280 
 281   return iterations;
 282 }
 283 
 284 void SafepointSynchronize::arm_safepoint() {
 285   // Begin the process of bringing the system to a safepoint.
 286   // Java threads can be in several different states and are
 287   // stopped by different mechanisms:
 288   //
 289   //  1. Running interpreted
 290   //     When executing branching/returning byte codes interpreter
 291   //     checks if the poll is armed, if so blocks in SS::block().
 292   //  2. Running in native code
 293   //     When returning from the native code, a Java thread must check
 294   //     the safepoint _state to see if we must block.  If the
 295   //     VM thread sees a Java thread in native, it does
 296   //     not wait for this thread to block.  The order of the memory
 297   //     writes and reads of both the safepoint state and the Java
 298   //     threads state is critical.  In order to guarantee that the
 299   //     memory writes are serialized with respect to each other,
 300   //     the VM thread issues a memory barrier instruction.
 301   //  3. Running compiled Code
 302   //     Compiled code reads the local polling page that
 303   //     is set to fault if we are trying to get to a safepoint.
 304   //  4. Blocked
 305   //     A thread which is blocked will not be allowed to return from the
 306   //     block condition until the safepoint operation is complete.
 307   //  5. In VM or Transitioning between states
 308   //     If a Java thread is currently running in the VM or transitioning
 309   //     between states, the safepointing code will poll the thread state
 310   //     until the thread blocks itself when it attempts transitions to a
 311   //     new state or locking a safepoint checked monitor.
 312 
 313   // We must never miss a thread with correct safepoint id, so we must make sure we arm
 314   // the wait barrier for the next safepoint id/counter.
 315   // Arming must be done after resetting _current_jni_active_count, _waiting_to_block.
 316   _wait_barrier->arm(static_cast<int>(_safepoint_counter + 1));
 317 
 318   assert((_safepoint_counter & 0x1) == 0, "must be even");
 319   // The store to _safepoint_counter must happen after any stores in arming.
 320   Atomic::release_store(&_safepoint_counter, _safepoint_counter + 1);
 321 
 322   // We are synchronizing
 323   OrderAccess::storestore(); // Ordered with _safepoint_counter
 324   _state = _synchronizing;
 325 
 326   // Arming the per thread poll while having _state != _not_synchronized means safepointing
 327   log_trace(safepoint)("Setting thread local yield flag for threads");
 328   OrderAccess::storestore(); // storestore, global state -> local state
 329   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur = jtiwh.next(); ) {
 330     // Make sure the threads start polling, it is time to yield.
 331     SafepointMechanism::arm_local_poll(cur);
 332   }
 333 
 334   OrderAccess::fence(); // storestore|storeload, global state -> local state
 335 }
 336 
 337 // Roll all threads forward to a safepoint and suspend them all
 338 void SafepointSynchronize::begin() {
 339   assert(Thread::current()->is_VM_thread(), "Only VM thread may execute a safepoint");
 340 
 341   EventSafepointBegin begin_event;
 342   SafepointTracing::begin(VMThread::vm_op_type());
 343 
 344   Universe::heap()->safepoint_synchronize_begin();
 345 
 346   // By getting the Threads_lock, we assure that no threads are about to start or
 347   // exit. It is released again in SafepointSynchronize::end().
 348   Threads_lock->lock();
 349 
 350   assert( _state == _not_synchronized, "trying to safepoint synchronize with wrong state");
 351 
 352   int nof_threads = Threads::number_of_threads();
 353 
 354   _nof_threads_hit_polling_page = 0;
 355 
 356   log_debug(safepoint)("Safepoint synchronization initiated using %s wait barrier. (%d threads)", _wait_barrier->description(), nof_threads);
 357 
 358   // Reset the count of active JNI critical threads
 359   _current_jni_active_count = 0;
 360 
 361   // Set number of threads to wait for
 362   _waiting_to_block = nof_threads;
 363 
 364   jlong safepoint_limit_time = 0;
 365   if (SafepointTimeout) {
 366     // Set the limit time, so that it can be compared to see if this has taken
 367     // too long to complete.
 368     safepoint_limit_time = SafepointTracing::start_of_safepoint() + (jlong)SafepointTimeoutDelay * (NANOUNITS / MILLIUNITS);
 369     timeout_error_printed = false;
 370   }
 371 
 372   EventSafepointStateSynchronization sync_event;
 373   int initial_running = 0;
 374 
 375   // Arms the safepoint, _current_jni_active_count and _waiting_to_block must be set before.
 376   arm_safepoint();
 377 
 378   // Will spin until all threads are safe.
 379   int iterations = synchronize_threads(safepoint_limit_time, nof_threads, &initial_running);
 380   assert(_waiting_to_block == 0, "No thread should be running");
 381 
 382 #ifndef PRODUCT
 383   if (safepoint_limit_time != 0) {
 384     jlong current_time = os::javaTimeNanos();
 385     if (safepoint_limit_time < current_time) {
 386       log_warning(safepoint)("# SafepointSynchronize: Finished after "
 387                     INT64_FORMAT_W(6) " ms",
 388                     (int64_t)(current_time - SafepointTracing::start_of_safepoint()) / (NANOUNITS / MILLIUNITS));
 389     }
 390   }
 391 #endif
 392 
 393   assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
 394 
 395   // Record state
 396   _state = _synchronized;
 397 
 398   OrderAccess::fence();
 399 
 400   // Set the new id
 401   ++_safepoint_id;
 402 
 403 #ifdef ASSERT
 404   // Make sure all the threads were visited.
 405   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur = jtiwh.next(); ) {
 406     assert(cur->was_visited_for_critical_count(_safepoint_counter), "missed a thread");
 407   }
 408 #endif // ASSERT
 409 
 410   // Update the count of active JNI critical regions
 411   GCLocker::set_jni_lock_count(_current_jni_active_count);
 412 
 413   post_safepoint_synchronize_event(sync_event,
 414                                    _safepoint_id,
 415                                    initial_running,
 416                                    _waiting_to_block, iterations);
 417 
 418   SafepointTracing::synchronized(nof_threads, initial_running, _nof_threads_hit_polling_page);
 419 
 420   // We do the safepoint cleanup first since a GC related safepoint
 421   // needs cleanup to be completed before running the GC op.
 422   EventSafepointCleanup cleanup_event;
 423   do_cleanup_tasks();
 424   post_safepoint_cleanup_event(cleanup_event, _safepoint_id);
 425 
 426   post_safepoint_begin_event(begin_event, _safepoint_id, nof_threads, _current_jni_active_count);
 427   SafepointTracing::cleanup();
 428 }
 429 
 430 void SafepointSynchronize::disarm_safepoint() {
 431   uint64_t active_safepoint_counter = _safepoint_counter;
 432   {
 433     JavaThreadIteratorWithHandle jtiwh;
 434 #ifdef ASSERT
 435     // A pending_exception cannot be installed during a safepoint.  The threads
 436     // may install an async exception after they come back from a safepoint into
 437     // pending_exception after they unblock.  But that should happen later.
 438     for (; JavaThread *cur = jtiwh.next(); ) {
 439       assert (!(cur->has_pending_exception() &&
 440                 cur->safepoint_state()->is_at_poll_safepoint()),
 441               "safepoint installed a pending exception");
 442     }
 443 #endif // ASSERT
 444 
 445     OrderAccess::fence(); // keep read and write of _state from floating up
 446     assert(_state == _synchronized, "must be synchronized before ending safepoint synchronization");
 447 
 448     // Change state first to _not_synchronized.
 449     // No threads should see _synchronized when running.
 450     _state = _not_synchronized;
 451 
 452     // Set the next dormant (even) safepoint id.
 453     assert((_safepoint_counter & 0x1) == 1, "must be odd");
 454     Atomic::release_store(&_safepoint_counter, _safepoint_counter + 1);
 455 
 456     OrderAccess::fence(); // Keep the local state from floating up.
 457 
 458     jtiwh.rewind();
 459     for (; JavaThread *current = jtiwh.next(); ) {
 460       // Clear the visited flag to ensure that the critical counts are collected properly.
 461       DEBUG_ONLY(current->reset_visited_for_critical_count(active_safepoint_counter);)
 462       ThreadSafepointState* cur_state = current->safepoint_state();
 463       assert(!cur_state->is_running(), "Thread not suspended at safepoint");
 464       cur_state->restart(); // TSS _running
 465       assert(cur_state->is_running(), "safepoint state has not been reset");
 466     }
 467   } // ~JavaThreadIteratorWithHandle
 468 
 469   // Release threads lock, so threads can be created/destroyed again.
 470   Threads_lock->unlock();
 471 
 472   // Wake threads after local state is correctly set.
 473   _wait_barrier->disarm();
 474 }
 475 
 476 // Wake up all threads, so they are ready to resume execution after the safepoint
 477 // operation has been carried out
 478 void SafepointSynchronize::end() {
 479   assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
 480   EventSafepointEnd event;
 481   assert(Thread::current()->is_VM_thread(), "Only VM thread can execute a safepoint");
 482 
 483   disarm_safepoint();
 484 
 485   Universe::heap()->safepoint_synchronize_end();
 486 
 487   SafepointTracing::end();
 488 
 489   post_safepoint_end_event(event, safepoint_id());
 490 }
 491 
 492 bool SafepointSynchronize::is_cleanup_needed() {
 493   // Need a cleanup safepoint if there are too many monitors in use
 494   // and the monitor deflation needs to be done at a safepoint.
 495   if (ObjectSynchronizer::is_safepoint_deflation_needed()) return true;
 496   // Need a safepoint if some inline cache buffers is non-empty
 497   if (!InlineCacheBuffer::is_empty()) return true;
 498   if (StringTable::needs_rehashing()) return true;
 499   if (SymbolTable::needs_rehashing()) return true;
 500   return false;
 501 }
 502 
 503 class ParallelSPCleanupThreadClosure : public ThreadClosure {
 504 private:
 505   DeflateMonitorCounters* _counters;
 506 
 507 public:
 508   ParallelSPCleanupThreadClosure(DeflateMonitorCounters* counters) :
 509     _counters(counters) {}
 510 
 511   void do_thread(Thread* thread) {
 512     // deflate_thread_local_monitors() handles or requests deflation of
 513     // this thread's idle monitors. If !AsyncDeflateIdleMonitors or if
 514     // there is a special cleanup request, deflation is handled now.
 515     // Otherwise, async deflation is requested via a flag.
 516     ObjectSynchronizer::deflate_thread_local_monitors(thread, _counters);
 517   }
 518 };
 519 
 520 class ParallelSPCleanupTask : public AbstractGangTask {
 521 private:
 522   SubTasksDone _subtasks;
 523   ParallelSPCleanupThreadClosure _cleanup_threads_cl;
 524   uint _num_workers;
 525   DeflateMonitorCounters* _counters;
 526 public:
 527   ParallelSPCleanupTask(uint num_workers, DeflateMonitorCounters* counters) :
 528     AbstractGangTask("Parallel Safepoint Cleanup"),
 529     _subtasks(SafepointSynchronize::SAFEPOINT_CLEANUP_NUM_TASKS),
 530     _cleanup_threads_cl(ParallelSPCleanupThreadClosure(counters)),
 531     _num_workers(num_workers),
 532     _counters(counters) {}
 533 
 534   void work(uint worker_id) {
 535     uint64_t safepoint_id = SafepointSynchronize::safepoint_id();
 536     // All threads deflate monitors and mark nmethods (if necessary).
 537     Threads::possibly_parallel_threads_do(true, &_cleanup_threads_cl);
 538 
 539     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_DEFLATE_MONITORS)) {
 540       const char* name = "deflating global idle monitors";
 541       EventSafepointCleanupTask event;
 542       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 543       // AsyncDeflateIdleMonitors only uses DeflateMonitorCounters
 544       // when a special cleanup has been requested.
 545       // Note: This logging output will include global idle monitor
 546       // elapsed times, but not global idle monitor deflation count.
 547       ObjectSynchronizer::do_safepoint_work(_counters);
 548 
 549       post_safepoint_cleanup_task_event(event, safepoint_id, name);
 550     }
 551 
 552     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_UPDATE_INLINE_CACHES)) {
 553       const char* name = "updating inline caches";
 554       EventSafepointCleanupTask event;
 555       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 556       InlineCacheBuffer::update_inline_caches();
 557 
 558       post_safepoint_cleanup_task_event(event, safepoint_id, name);
 559     }
 560 
 561     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_COMPILATION_POLICY)) {
 562       const char* name = "compilation policy safepoint handler";
 563       EventSafepointCleanupTask event;
 564       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 565       CompilationPolicy::policy()->do_safepoint_work();
 566 
 567       post_safepoint_cleanup_task_event(event, safepoint_id, name);
 568     }
 569 
 570     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_SYMBOL_TABLE_REHASH)) {
 571       if (SymbolTable::needs_rehashing()) {
 572         const char* name = "rehashing symbol table";
 573         EventSafepointCleanupTask event;
 574         TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 575         SymbolTable::rehash_table();
 576 
 577         post_safepoint_cleanup_task_event(event, safepoint_id, name);
 578       }
 579     }
 580 
 581     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_STRING_TABLE_REHASH)) {
 582       if (StringTable::needs_rehashing()) {
 583         const char* name = "rehashing string table";
 584         EventSafepointCleanupTask event;
 585         TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 586         StringTable::rehash_table();
 587 
 588         post_safepoint_cleanup_task_event(event, safepoint_id, name);
 589       }
 590     }
 591 
 592     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_SYSTEM_DICTIONARY_RESIZE)) {
 593       if (Dictionary::does_any_dictionary_needs_resizing()) {
 594         const char* name = "resizing system dictionaries";
 595         EventSafepointCleanupTask event;
 596         TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 597         ClassLoaderDataGraph::resize_dictionaries();
 598 
 599         post_safepoint_cleanup_task_event(event, safepoint_id, name);
 600       }
 601     }
 602 
 603     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_REQUEST_OOPSTORAGE_CLEANUP)) {
 604       // Don't bother reporting event or time for this very short operation.
 605       // To have any utility we'd also want to report whether needed.
 606       OopStorage::trigger_cleanup_if_needed();
 607     }
 608 
 609     _subtasks.all_tasks_completed(_num_workers);
 610   }
 611 };
 612 
 613 // Various cleaning tasks that should be done periodically at safepoints.
 614 void SafepointSynchronize::do_cleanup_tasks() {
 615 
 616   TraceTime timer("safepoint cleanup tasks", TRACETIME_LOG(Info, safepoint, cleanup));
 617 
 618   // Prepare for monitor deflation.
 619   DeflateMonitorCounters deflate_counters;
 620   ObjectSynchronizer::prepare_deflate_idle_monitors(&deflate_counters);
 621 
 622   CollectedHeap* heap = Universe::heap();
 623   assert(heap != NULL, "heap not initialized yet?");
 624   WorkGang* cleanup_workers = heap->get_safepoint_workers();
 625   if (cleanup_workers != NULL) {
 626     // Parallel cleanup using GC provided thread pool.
 627     uint num_cleanup_workers = cleanup_workers->active_workers();
 628     ParallelSPCleanupTask cleanup(num_cleanup_workers, &deflate_counters);
 629     StrongRootsScope srs(num_cleanup_workers);
 630     cleanup_workers->run_task(&cleanup);
 631   } else {
 632     // Serial cleanup using VMThread.
 633     ParallelSPCleanupTask cleanup(1, &deflate_counters);
 634     StrongRootsScope srs(1);
 635     cleanup.work(0);
 636   }
 637 
 638   // Needs to be done single threaded by the VMThread.  This walks
 639   // the thread stacks looking for references to metadata before
 640   // deciding to remove it from the metaspaces.
 641   if (ClassLoaderDataGraph::should_clean_metaspaces_and_reset()) {
 642     const char* name = "cleanup live ClassLoaderData metaspaces";
 643     TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 644     ClassLoaderDataGraph::walk_metadata_and_clean_metaspaces();
 645   }
 646 
 647   // Finish monitor deflation.
 648   ObjectSynchronizer::finish_deflate_idle_monitors(&deflate_counters);
 649 
 650   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
 651 }
 652 
 653 // Methods for determining if a JavaThread is safepoint safe.
 654 
 655 // False means unsafe with undetermined state.
 656 // True means a determined state, but it may be an unsafe state.
 657 // If called from a non-safepoint context safepoint_count MUST be InactiveSafepointCounter.
 658 bool SafepointSynchronize::try_stable_load_state(JavaThreadState *state, JavaThread *thread, uint64_t safepoint_count) {
 659   assert((safepoint_count != InactiveSafepointCounter &&
 660           Thread::current() == (Thread*)VMThread::vm_thread() &&
 661           SafepointSynchronize::_state != _not_synchronized)
 662          || safepoint_count == InactiveSafepointCounter, "Invalid check");
 663 
 664   // To handle the thread_blocked state on the backedge of the WaitBarrier from
 665   // previous safepoint and reading the reset value (0/InactiveSafepointCounter) we
 666   // re-read state after we read thread safepoint id. The JavaThread changes its
 667   // thread state from thread_blocked before resetting safepoint id to 0.
 668   // This guarantees the second read will be from an updated thread state. It can
 669   // either be different state making this an unsafe state or it can see blocked
 670   // again. When we see blocked twice with a 0 safepoint id, either:
 671   // - It is normally blocked, e.g. on Mutex, TBIVM.
 672   // - It was in SS:block(), looped around to SS:block() and is blocked on the WaitBarrier.
 673   // - It was in SS:block() but now on a Mutex.
 674   // All of these cases are safe.
 675 
 676   *state = thread->thread_state();
 677   OrderAccess::loadload();
 678   uint64_t sid = thread->safepoint_state()->get_safepoint_id();  // Load acquire
 679   if (sid != InactiveSafepointCounter && sid != safepoint_count) {
 680     // In an old safepoint, state not relevant.
 681     return false;
 682   }
 683   return *state == thread->thread_state();
 684 }
 685 
 686 static bool safepoint_safe_with(JavaThread *thread, JavaThreadState state) {
 687   switch(state) {
 688   case _thread_in_native:
 689     // native threads are safe if they have no java stack or have walkable stack
 690     return !thread->has_last_Java_frame() || thread->frame_anchor()->walkable();
 691 
 692   case _thread_blocked:
 693     // On wait_barrier or blocked.
 694     // Blocked threads should already have walkable stack.
 695     assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "blocked and not walkable");
 696     return true;
 697 
 698   default:
 699     return false;
 700   }
 701 }
 702 
 703 bool SafepointSynchronize::handshake_safe(JavaThread *thread) {
 704   if (thread->is_ext_suspended() || thread->is_terminated()) {
 705     return true;
 706   }
 707   JavaThreadState stable_state;
 708   if (try_stable_load_state(&stable_state, thread, InactiveSafepointCounter)) {
 709     return safepoint_safe_with(thread, stable_state);
 710   }
 711   return false;
 712 }
 713 
 714 // See if the thread is running inside a lazy critical native and
 715 // update the thread critical count if so.  Also set a suspend flag to
 716 // cause the native wrapper to return into the JVM to do the unlock
 717 // once the native finishes.
 718 static void check_for_lazy_critical_native(JavaThread *thread, JavaThreadState state) {
 719   if (state == _thread_in_native &&
 720       thread->has_last_Java_frame() &&
 721       thread->frame_anchor()->walkable()) {
 722     // This thread might be in a critical native nmethod so look at
 723     // the top of the stack and increment the critical count if it
 724     // is.
 725     frame wrapper_frame = thread->last_frame();
 726     CodeBlob* stub_cb = wrapper_frame.cb();
 727     if (stub_cb != NULL &&
 728         stub_cb->is_nmethod() &&
 729         stub_cb->as_nmethod_or_null()->is_lazy_critical_native()) {
 730       // A thread could potentially be in a critical native across
 731       // more than one safepoint, so only update the critical state on
 732       // the first one.  When it returns it will perform the unlock.
 733       if (!thread->do_critical_native_unlock()) {
 734 #ifdef ASSERT
 735         if (!thread->in_critical()) {
 736           GCLocker::increment_debug_jni_lock_count();
 737         }
 738 #endif
 739         thread->enter_critical();
 740         // Make sure the native wrapper calls back on return to
 741         // perform the needed critical unlock.
 742         thread->set_critical_native_unlock();
 743       }
 744     }
 745   }
 746 }
 747 
 748 // -------------------------------------------------------------------------------------------------------
 749 // Implementation of Safepoint blocking point
 750 
 751 void SafepointSynchronize::block(JavaThread *thread) {
 752   assert(thread != NULL, "thread must be set");
 753   assert(thread->is_Java_thread(), "not a Java thread");
 754 
 755   // Threads shouldn't block if they are in the middle of printing, but...
 756   ttyLocker::break_tty_lock_for_safepoint(os::current_thread_id());
 757 
 758   // Only bail from the block() call if the thread is gone from the
 759   // thread list; starting to exit should still block.
 760   if (thread->is_terminated()) {
 761      // block current thread if we come here from native code when VM is gone
 762      thread->block_if_vm_exited();
 763 
 764      // otherwise do nothing
 765      return;
 766   }
 767 
 768   JavaThreadState state = thread->thread_state();
 769   thread->frame_anchor()->make_walkable(thread);
 770 
 771   uint64_t safepoint_id = SafepointSynchronize::safepoint_counter();
 772   // Check that we have a valid thread_state at this point
 773   switch(state) {
 774     case _thread_in_vm_trans:
 775     case _thread_in_Java:        // From compiled code
 776     case _thread_in_native_trans:
 777     case _thread_blocked_trans:
 778     case _thread_new_trans:
 779 
 780       // We have no idea where the VMThread is, it might even be at next safepoint.
 781       // So we can miss this poll, but stop at next.
 782 
 783       // Load dependent store, it must not pass loading of safepoint_id.
 784       thread->safepoint_state()->set_safepoint_id(safepoint_id); // Release store
 785 
 786       // This part we can skip if we notice we miss or are in a future safepoint.
 787       OrderAccess::storestore();
 788       // Load in wait barrier should not float up
 789       thread->set_thread_state_fence(_thread_blocked);
 790 
 791       _wait_barrier->wait(static_cast<int>(safepoint_id));
 792       assert(_state != _synchronized, "Can't be");
 793 
 794       // If barrier is disarmed stop store from floating above loads in barrier.
 795       OrderAccess::loadstore();
 796       thread->set_thread_state(state);
 797 
 798       // Then we reset the safepoint id to inactive.
 799       thread->safepoint_state()->reset_safepoint_id(); // Release store
 800 
 801       OrderAccess::fence();
 802 
 803       break;
 804 
 805     default:
 806      fatal("Illegal threadstate encountered: %d", state);
 807   }
 808   guarantee(thread->safepoint_state()->get_safepoint_id() == InactiveSafepointCounter,
 809             "The safepoint id should be set only in block path");
 810 
 811   // Check for pending. async. exceptions or suspends - except if the
 812   // thread was blocked inside the VM. has_special_runtime_exit_condition()
 813   // is called last since it grabs a lock and we only want to do that when
 814   // we must.
 815   //
 816   // Note: we never deliver an async exception at a polling point as the
 817   // compiler may not have an exception handler for it. The polling
 818   // code will notice the async and deoptimize and the exception will
 819   // be delivered. (Polling at a return point is ok though). Sure is
 820   // a lot of bother for a deprecated feature...
 821   //
 822   // We don't deliver an async exception if the thread state is
 823   // _thread_in_native_trans so JNI functions won't be called with
 824   // a surprising pending exception. If the thread state is going back to java,
 825   // async exception is checked in check_special_condition_for_native_trans().
 826 
 827   if (state != _thread_blocked_trans &&
 828       state != _thread_in_vm_trans &&
 829       thread->has_special_runtime_exit_condition()) {
 830     thread->handle_special_runtime_exit_condition(
 831       !thread->is_at_poll_safepoint() && (state != _thread_in_native_trans));
 832   }
 833 
 834   // cross_modify_fence is done by SafepointMechanism::block_if_requested_slow
 835   // which is the only caller here.
 836 }
 837 
 838 // ------------------------------------------------------------------------------------------------------
 839 // Exception handlers
 840 
 841 
 842 void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
 843   assert(thread->is_Java_thread(), "polling reference encountered by VM thread");
 844   assert(thread->thread_state() == _thread_in_Java, "should come from Java code");
 845 
 846   if (log_is_enabled(Info, safepoint, stats)) {
 847     Atomic::inc(&_nof_threads_hit_polling_page);
 848   }
 849 
 850   ThreadSafepointState* state = thread->safepoint_state();
 851 
 852   state->handle_polling_page_exception();
 853 }
 854 
 855 
 856 void SafepointSynchronize::print_safepoint_timeout() {
 857   if (!timeout_error_printed) {
 858     timeout_error_printed = true;
 859     // Print out the thread info which didn't reach the safepoint for debugging
 860     // purposes (useful when there are lots of threads in the debugger).
 861     LogTarget(Warning, safepoint) lt;
 862     if (lt.is_enabled()) {
 863       ResourceMark rm;
 864       LogStream ls(lt);
 865 
 866       ls.cr();
 867       ls.print_cr("# SafepointSynchronize::begin: Timeout detected:");
 868       ls.print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint.");
 869       ls.print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:");
 870       for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur_thread = jtiwh.next(); ) {
 871         if (cur_thread->safepoint_state()->is_running()) {
 872           ls.print("# ");
 873           cur_thread->print_on(&ls);
 874           ls.cr();
 875         }
 876       }
 877       ls.print_cr("# SafepointSynchronize::begin: (End of list)");
 878     }
 879   }
 880 
 881   // To debug the long safepoint, specify both AbortVMOnSafepointTimeout &
 882   // ShowMessageBoxOnError.
 883   if (AbortVMOnSafepointTimeout) {
 884     // Send the blocking thread a signal to terminate and write an error file.
 885     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur_thread = jtiwh.next(); ) {
 886       if (cur_thread->safepoint_state()->is_running()) {
 887         if (!os::signal_thread(cur_thread, SIGILL, "blocking a safepoint")) {
 888           break; // Could not send signal. Report fatal error.
 889         }
 890         // Give cur_thread a chance to report the error and terminate the VM.
 891         os::naked_sleep(3000);
 892       }
 893     }
 894     fatal("Safepoint sync time longer than " INTX_FORMAT "ms detected when executing %s.",
 895           SafepointTimeoutDelay, VMThread::vm_operation()->name());
 896   }
 897 }
 898 
 899 // -------------------------------------------------------------------------------------------------------
 900 // Implementation of ThreadSafepointState
 901 
 902 ThreadSafepointState::ThreadSafepointState(JavaThread *thread)
 903   : _at_poll_safepoint(false), _thread(thread), _safepoint_safe(false),
 904     _safepoint_id(SafepointSynchronize::InactiveSafepointCounter), _next(NULL) {
 905 }
 906 
 907 void ThreadSafepointState::create(JavaThread *thread) {
 908   ThreadSafepointState *state = new ThreadSafepointState(thread);
 909   thread->set_safepoint_state(state);
 910 }
 911 
 912 void ThreadSafepointState::destroy(JavaThread *thread) {
 913   if (thread->safepoint_state()) {
 914     delete(thread->safepoint_state());
 915     thread->set_safepoint_state(NULL);
 916   }
 917 }
 918 
 919 uint64_t ThreadSafepointState::get_safepoint_id() const {
 920   return Atomic::load_acquire(&_safepoint_id);
 921 }
 922 
 923 void ThreadSafepointState::reset_safepoint_id() {
 924   Atomic::release_store(&_safepoint_id, SafepointSynchronize::InactiveSafepointCounter);
 925 }
 926 
 927 void ThreadSafepointState::set_safepoint_id(uint64_t safepoint_id) {
 928   Atomic::release_store(&_safepoint_id, safepoint_id);
 929 }
 930 
 931 void ThreadSafepointState::examine_state_of_thread(uint64_t safepoint_count) {
 932   assert(is_running(), "better be running or just have hit safepoint poll");
 933 
 934   JavaThreadState stable_state;
 935   if (!SafepointSynchronize::try_stable_load_state(&stable_state, _thread, safepoint_count)) {
 936     // We could not get stable state of the JavaThread.
 937     // Consider it running and just return.
 938     return;
 939   }
 940 
 941   // Check for a thread that is suspended. Note that thread resume tries
 942   // to grab the Threads_lock which we own here, so a thread cannot be
 943   // resumed during safepoint synchronization.
 944 
 945   // We check to see if this thread is suspended without locking to
 946   // avoid deadlocking with a third thread that is waiting for this
 947   // thread to be suspended. The third thread can notice the safepoint
 948   // that we're trying to start at the beginning of its SR_lock->wait()
 949   // call. If that happens, then the third thread will block on the
 950   // safepoint while still holding the underlying SR_lock. We won't be
 951   // able to get the SR_lock and we'll deadlock.
 952   //
 953   // We don't need to grab the SR_lock here for two reasons:
 954   // 1) The suspend flags are both volatile and are set with an
 955   //    Atomic::cmpxchg() call so we should see the suspended
 956   //    state right away.
 957   // 2) We're being called from the safepoint polling loop; if
 958   //    we don't see the suspended state on this iteration, then
 959   //    we'll come around again.
 960   //
 961   bool is_suspended = _thread->is_ext_suspended();
 962   if (is_suspended) {
 963     account_safe_thread();
 964     return;
 965   }
 966 
 967   if (safepoint_safe_with(_thread, stable_state)) {
 968     check_for_lazy_critical_native(_thread, stable_state);
 969     account_safe_thread();
 970     return;
 971   }
 972 
 973   // All other thread states will continue to run until they
 974   // transition and self-block in state _blocked
 975   // Safepoint polling in compiled code causes the Java threads to do the same.
 976   // Note: new threads may require a malloc so they must be allowed to finish
 977 
 978   assert(is_running(), "examine_state_of_thread on non-running thread");
 979   return;
 980 }
 981 
 982 void ThreadSafepointState::account_safe_thread() {
 983   SafepointSynchronize::decrement_waiting_to_block();
 984   if (_thread->in_critical()) {
 985     // Notice that this thread is in a critical section
 986     SafepointSynchronize::increment_jni_active_count();
 987   }
 988   DEBUG_ONLY(_thread->set_visited_for_critical_count(SafepointSynchronize::safepoint_counter());)
 989   assert(!_safepoint_safe, "Must be unsafe before safe");
 990   _safepoint_safe = true;
 991 }
 992 
 993 void ThreadSafepointState::restart() {
 994   assert(_safepoint_safe, "Must be safe before unsafe");
 995   _safepoint_safe = false;
 996 }
 997 
 998 void ThreadSafepointState::print_on(outputStream *st) const {
 999   const char *s = _safepoint_safe ? "_at_safepoint" : "_running";
1000 
1001   st->print_cr("Thread: " INTPTR_FORMAT
1002               "  [0x%2x] State: %s _at_poll_safepoint %d",
1003                p2i(_thread), _thread->osthread()->thread_id(), s, _at_poll_safepoint);
1004 
1005   _thread->print_thread_state_on(st);
1006 }
1007 
1008 // ---------------------------------------------------------------------------------------------------------------------
1009 
1010 // Block the thread at poll or poll return for safepoint/handshake.
1011 void ThreadSafepointState::handle_polling_page_exception() {
1012 
1013   // Step 1: Find the nmethod from the return address
1014   address real_return_addr = thread()->saved_exception_pc();
1015 
1016   CodeBlob *cb = CodeCache::find_blob(real_return_addr);
1017   assert(cb != NULL && cb->is_compiled(), "return address should be in nmethod");
1018   CompiledMethod* nm = (CompiledMethod*)cb;
1019 
1020   // Find frame of caller
1021   frame stub_fr = thread()->last_frame();
1022   CodeBlob* stub_cb = stub_fr.cb();
1023   assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub");
1024   RegisterMap map(thread(), true);
1025   frame caller_fr = stub_fr.sender(&map);
1026 
1027   // Should only be poll_return or poll
1028   assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" );
1029 
1030   // This is a poll immediately before a return. The exception handling code
1031   // has already had the effect of causing the return to occur, so the execution
1032   // will continue immediately after the call. In addition, the oopmap at the
1033   // return point does not mark the return value as an oop (if it is), so
1034   // it needs a handle here to be updated.
1035   if( nm->is_at_poll_return(real_return_addr) ) {
1036     // See if return type is an oop.
1037     bool return_oop = nm->method()->is_returning_oop();
1038     Handle return_value;
1039     if (return_oop) {
1040       // The oop result has been saved on the stack together with all
1041       // the other registers. In order to preserve it over GCs we need
1042       // to keep it in a handle.
1043       oop result = caller_fr.saved_oop_result(&map);
1044       assert(oopDesc::is_oop_or_null(result), "must be oop");
1045       return_value = Handle(thread(), result);
1046       assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
1047     }
1048 
1049     // Block the thread
1050     SafepointMechanism::block_if_requested(thread());
1051 
1052     // restore oop result, if any
1053     if (return_oop) {
1054       caller_fr.set_saved_oop_result(&map, return_value());
1055     }
1056   }
1057 
1058   // This is a safepoint poll. Verify the return address and block.
1059   else {
1060     set_at_poll_safepoint(true);
1061 
1062     // verify the blob built the "return address" correctly
1063     assert(real_return_addr == caller_fr.pc(), "must match");
1064 
1065     // Block the thread
1066     SafepointMechanism::block_if_requested(thread());
1067     set_at_poll_safepoint(false);
1068 
1069     // If we have a pending async exception deoptimize the frame
1070     // as otherwise we may never deliver it.
1071     if (thread()->has_async_condition()) {
1072       ThreadInVMfromJavaNoAsyncException __tiv(thread());
1073       Deoptimization::deoptimize_frame(thread(), caller_fr.id());
1074     }
1075 
1076     // If an exception has been installed we must check for a pending deoptimization
1077     // Deoptimize frame if exception has been thrown.
1078 
1079     if (thread()->has_pending_exception() ) {
1080       RegisterMap map(thread(), true);
1081       frame caller_fr = stub_fr.sender(&map);
1082       if (caller_fr.is_deoptimized_frame()) {
1083         // The exception patch will destroy registers that are still
1084         // live and will be needed during deoptimization. Defer the
1085         // Async exception should have deferred the exception until the
1086         // next safepoint which will be detected when we get into
1087         // the interpreter so if we have an exception now things
1088         // are messed up.
1089 
1090         fatal("Exception installed and deoptimization is pending");
1091       }
1092     }
1093   }
1094 }
1095 
1096 
1097 // -------------------------------------------------------------------------------------------------------
1098 // Implementation of SafepointTracing
1099 
1100 jlong SafepointTracing::_last_safepoint_begin_time_ns = 0;
1101 jlong SafepointTracing::_last_safepoint_sync_time_ns = 0;
1102 jlong SafepointTracing::_last_safepoint_cleanup_time_ns = 0;
1103 jlong SafepointTracing::_last_safepoint_end_time_ns = 0;
1104 jlong SafepointTracing::_last_app_time_ns = 0;
1105 int SafepointTracing::_nof_threads = 0;
1106 int SafepointTracing::_nof_running = 0;
1107 int SafepointTracing::_page_trap = 0;
1108 VM_Operation::VMOp_Type SafepointTracing::_current_type;
1109 jlong     SafepointTracing::_max_sync_time = 0;
1110 jlong     SafepointTracing::_max_vmop_time = 0;
1111 uint64_t  SafepointTracing::_op_count[VM_Operation::VMOp_Terminating] = {0};
1112 
1113 void SafepointTracing::init() {
1114   // Application start
1115   _last_safepoint_end_time_ns = os::javaTimeNanos();
1116 }
1117 
1118 // Helper method to print the header.
1119 static void print_header(outputStream* st) {
1120   // The number of spaces is significant here, and should match the format
1121   // specifiers in print_statistics().
1122 
1123   st->print("VM Operation                 "
1124             "[ threads: total initial_running ]"
1125             "[ time:       sync    cleanup       vmop      total ]");
1126 
1127   st->print_cr(" page_trap_count");
1128 }
1129 
1130 // This prints a nice table.  To get the statistics to not shift due to the logging uptime
1131 // decorator, use the option as: -Xlog:safepoint+stats:[outputfile]:none
1132 void SafepointTracing::statistics_log() {
1133   LogTarget(Info, safepoint, stats) lt;
1134   assert (lt.is_enabled(), "should only be called when printing statistics is enabled");
1135   LogStream ls(lt);
1136 
1137   static int _cur_stat_index = 0;
1138 
1139   // Print header every 30 entries
1140   if ((_cur_stat_index % 30) == 0) {
1141     print_header(&ls);
1142     _cur_stat_index = 1;  // wrap
1143   } else {
1144     _cur_stat_index++;
1145   }
1146 
1147   ls.print("%-28s [       "
1148            INT32_FORMAT_W(8) "        " INT32_FORMAT_W(8) " "
1149            "]",
1150            VM_Operation::name(_current_type),
1151            _nof_threads,
1152            _nof_running);
1153   ls.print("[       "
1154            INT64_FORMAT_W(10) " " INT64_FORMAT_W(10) " "
1155            INT64_FORMAT_W(10) " " INT64_FORMAT_W(10) " ]",
1156            (int64_t)(_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns),
1157            (int64_t)(_last_safepoint_cleanup_time_ns - _last_safepoint_sync_time_ns),
1158            (int64_t)(_last_safepoint_end_time_ns - _last_safepoint_cleanup_time_ns),
1159            (int64_t)(_last_safepoint_end_time_ns - _last_safepoint_begin_time_ns));
1160 
1161   ls.print_cr(INT32_FORMAT_W(16), _page_trap);
1162 }
1163 
1164 // This method will be called when VM exits. This tries to summarize the sampling.
1165 // Current thread may already be deleted, so don't use ResourceMark.
1166 void SafepointTracing::statistics_exit_log() {
1167   if (!log_is_enabled(Info, safepoint, stats)) {
1168     return;
1169   }
1170   for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) {
1171     if (_op_count[index] != 0) {
1172       log_info(safepoint, stats)("%-28s" UINT64_FORMAT_W(10), VM_Operation::name(index),
1173                _op_count[index]);
1174     }
1175   }
1176 
1177   log_info(safepoint, stats)("Maximum sync time  " INT64_FORMAT" ns",
1178                               (int64_t)(_max_sync_time));
1179   log_info(safepoint, stats)("Maximum vm operation time (except for Exit VM operation)  "
1180                               INT64_FORMAT " ns",
1181                               (int64_t)(_max_vmop_time));
1182 }
1183 
1184 void SafepointTracing::begin(VM_Operation::VMOp_Type type) {
1185   _op_count[type]++;
1186   _current_type = type;
1187 
1188   // update the time stamp to begin recording safepoint time
1189   _last_safepoint_begin_time_ns = os::javaTimeNanos();
1190   _last_safepoint_sync_time_ns = 0;
1191   _last_safepoint_cleanup_time_ns = 0;
1192 
1193   _last_app_time_ns = _last_safepoint_begin_time_ns - _last_safepoint_end_time_ns;
1194   _last_safepoint_end_time_ns = 0;
1195 
1196   RuntimeService::record_safepoint_begin(_last_app_time_ns);
1197 }
1198 
1199 void SafepointTracing::synchronized(int nof_threads, int nof_running, int traps) {
1200   _last_safepoint_sync_time_ns = os::javaTimeNanos();
1201   _nof_threads = nof_threads;
1202   _nof_running = nof_running;
1203   _page_trap   = traps;
1204   RuntimeService::record_safepoint_synchronized(_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns);
1205 }
1206 
1207 void SafepointTracing::cleanup() {
1208   _last_safepoint_cleanup_time_ns = os::javaTimeNanos();
1209 }
1210 
1211 void SafepointTracing::end() {
1212   _last_safepoint_end_time_ns = os::javaTimeNanos();
1213 
1214   if (_max_sync_time < (_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns)) {
1215     _max_sync_time = _last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns;
1216   }
1217   if (_max_vmop_time < (_last_safepoint_end_time_ns - _last_safepoint_sync_time_ns)) {
1218     _max_vmop_time = _last_safepoint_end_time_ns - _last_safepoint_sync_time_ns;
1219   }
1220   if (log_is_enabled(Info, safepoint, stats)) {
1221     statistics_log();
1222   }
1223 
1224   log_info(safepoint)(
1225      "Safepoint \"%s\", "
1226      "Time since last: " JLONG_FORMAT " ns, "
1227      "Reaching safepoint: " JLONG_FORMAT " ns, "
1228      "At safepoint: " JLONG_FORMAT " ns, "
1229      "Total: " JLONG_FORMAT " ns",
1230       VM_Operation::name(_current_type),
1231       _last_app_time_ns,
1232       _last_safepoint_cleanup_time_ns - _last_safepoint_begin_time_ns,
1233       _last_safepoint_end_time_ns     - _last_safepoint_cleanup_time_ns,
1234       _last_safepoint_end_time_ns     - _last_safepoint_begin_time_ns
1235      );
1236 
1237   RuntimeService::record_safepoint_end(_last_safepoint_end_time_ns - _last_safepoint_cleanup_time_ns);
1238 }