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