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