1 /*
   2  * Copyright (c) 1997, 2023, 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                                              int 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(checked_cast<u4>(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 != nullptr) {
 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 = nullptr;
 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() == nullptr, "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 = nullptr;
 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 == nullptr, "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 != nullptr) {
 268       assert(cur_tss->is_running(), "Illegal initial state");
 269       if (thread_not_running(cur_tss)) {
 270         --still_running;
 271         *p_prev = nullptr;
 272         ThreadSafepointState *tmp = cur_tss;
 273         cur_tss = cur_tss->get_next();
 274         tmp->set_next(nullptr);
 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 == nullptr, "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 * NANOSECS_PER_MILLISEC);
 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   uint expected_num_workers() const {
 552     uint workers = 0;
 553 
 554     if (SymbolTable::rehash_table_expects_safepoint_rehashing()) {
 555       workers++;
 556     }
 557 
 558     if (StringTable::rehash_table_expects_safepoint_rehashing()) {
 559       workers++;
 560     }
 561 
 562     if (InlineCacheBuffer::needs_update_inline_caches()) {
 563       workers++;
 564     }
 565 
 566     if (_do_lazy_roots) {
 567       workers++;
 568     }
 569 
 570     return MAX2<uint>(1, workers);
 571   }
 572 
 573   void work(uint worker_id) {
 574     // These tasks are ordered by relative length of time to execute so that potentially longer tasks start first.
 575     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_SYMBOL_TABLE_REHASH)) {
 576       if (SymbolTable::needs_rehashing()) {
 577         Tracer t("rehashing symbol table");
 578         SymbolTable::rehash_table();
 579       }
 580     }
 581 
 582     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_STRING_TABLE_REHASH)) {
 583       if (StringTable::needs_rehashing()) {
 584         Tracer t("rehashing string table");
 585         StringTable::rehash_table();
 586       }
 587     }
 588 
 589     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_LAZY_ROOT_PROCESSING)) {
 590       if (_do_lazy_roots) {
 591         Tracer t("lazy partial thread root processing");
 592         class LazyRootClosure : public ThreadClosure {
 593         public:
 594           void do_thread(Thread* thread) {
 595             StackWatermarkSet::start_processing(JavaThread::cast(thread), StackWatermarkKind::gc);
 596           }
 597         };
 598         LazyRootClosure cl;
 599         Threads::java_threads_do(&cl);
 600       }
 601     }
 602 
 603     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_UPDATE_INLINE_CACHES)) {
 604       Tracer t("updating inline caches");
 605       InlineCacheBuffer::update_inline_caches();
 606     }
 607 
 608     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_REQUEST_OOPSTORAGE_CLEANUP)) {
 609       // Don't bother reporting event or time for this very short operation.
 610       // To have any utility we'd also want to report whether needed.
 611       OopStorage::trigger_cleanup_if_needed();
 612     }
 613 
 614     _subtasks.all_tasks_claimed();
 615   }
 616 };
 617 
 618 // Various cleaning tasks that should be done periodically at safepoints.
 619 void SafepointSynchronize::do_cleanup_tasks() {
 620 
 621   TraceTime timer("safepoint cleanup tasks", TRACETIME_LOG(Info, safepoint, cleanup));
 622 
 623   CollectedHeap* heap = Universe::heap();
 624   assert(heap != nullptr, "heap not initialized yet?");
 625   ParallelCleanupTask cleanup;
 626   WorkerThreads* cleanup_workers = heap->safepoint_workers();
 627   const uint expected_num_workers = cleanup.expected_num_workers();
 628   if (cleanup_workers != nullptr && expected_num_workers > 1) {
 629     // Parallel cleanup using GC provided thread pool.
 630     const uint num_workers = MIN2(expected_num_workers, cleanup_workers->active_workers());
 631     cleanup_workers->run_task(&cleanup, num_workers);
 632   } else {
 633     // Serial cleanup using VMThread.
 634     cleanup.work(0);
 635   }
 636 
 637   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
 638 
 639   if (log_is_enabled(Debug, monitorinflation)) {
 640     // The VMThread calls do_final_audit_and_print_stats() which calls
 641     // audit_and_print_stats() at the Info level at VM exit time.
 642     ObjectSynchronizer::audit_and_print_stats(false /* on_exit */);
 643   }
 644 }
 645 
 646 // Methods for determining if a JavaThread is safepoint safe.
 647 
 648 // False means unsafe with undetermined state.
 649 // True means a determined state, but it may be an unsafe state.
 650 // If called from a non-safepoint context safepoint_count MUST be InactiveSafepointCounter.
 651 bool SafepointSynchronize::try_stable_load_state(JavaThreadState *state, JavaThread *thread, uint64_t safepoint_count) {
 652   assert((safepoint_count != InactiveSafepointCounter &&
 653           Thread::current() == (Thread*)VMThread::vm_thread() &&
 654           SafepointSynchronize::_state != _not_synchronized)
 655          || safepoint_count == InactiveSafepointCounter, "Invalid check");
 656 
 657   // To handle the thread_blocked state on the backedge of the WaitBarrier from
 658   // previous safepoint and reading the reset value (0/InactiveSafepointCounter) we
 659   // re-read state after we read thread safepoint id. The JavaThread changes its
 660   // thread state from thread_blocked before resetting safepoint id to 0.
 661   // This guarantees the second read will be from an updated thread state. It can
 662   // either be different state making this an unsafe state or it can see blocked
 663   // again. When we see blocked twice with a 0 safepoint id, either:
 664   // - It is normally blocked, e.g. on Mutex, TBIVM.
 665   // - It was in SS:block(), looped around to SS:block() and is blocked on the WaitBarrier.
 666   // - It was in SS:block() but now on a Mutex.
 667   // All of these cases are safe.
 668 
 669   *state = thread->thread_state();
 670   OrderAccess::loadload();
 671   uint64_t sid = thread->safepoint_state()->get_safepoint_id();  // Load acquire
 672   if (sid != InactiveSafepointCounter && sid != safepoint_count) {
 673     // In an old safepoint, state not relevant.
 674     return false;
 675   }
 676   return *state == thread->thread_state();
 677 }
 678 
 679 static bool safepoint_safe_with(JavaThread *thread, JavaThreadState state) {
 680   switch(state) {
 681   case _thread_in_native:
 682     // native threads are safe if they have no java stack or have walkable stack
 683     return !thread->has_last_Java_frame() || thread->frame_anchor()->walkable();
 684 
 685   case _thread_blocked:
 686     // On wait_barrier or blocked.
 687     // Blocked threads should already have walkable stack.
 688     assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "blocked and not walkable");
 689     return true;
 690 
 691   default:
 692     return false;
 693   }
 694 }
 695 
 696 bool SafepointSynchronize::handshake_safe(JavaThread *thread) {
 697   if (thread->is_terminated()) {
 698     return true;
 699   }
 700   JavaThreadState stable_state;
 701   if (try_stable_load_state(&stable_state, thread, InactiveSafepointCounter)) {
 702     return safepoint_safe_with(thread, stable_state);
 703   }
 704   return false;
 705 }
 706 
 707 
 708 // -------------------------------------------------------------------------------------------------------
 709 // Implementation of Safepoint blocking point
 710 
 711 void SafepointSynchronize::block(JavaThread *thread) {
 712   assert(thread != nullptr, "thread must be set");
 713 
 714   // Threads shouldn't block if they are in the middle of printing, but...
 715   ttyLocker::break_tty_lock_for_safepoint(os::current_thread_id());
 716 
 717   // Only bail from the block() call if the thread is gone from the
 718   // thread list; starting to exit should still block.
 719   if (thread->is_terminated()) {
 720      // block current thread if we come here from native code when VM is gone
 721      thread->block_if_vm_exited();
 722 
 723      // otherwise do nothing
 724      return;
 725   }
 726 
 727   JavaThreadState state = thread->thread_state();
 728   thread->frame_anchor()->make_walkable();
 729 
 730   uint64_t safepoint_id = SafepointSynchronize::safepoint_counter();
 731 
 732   // We have no idea where the VMThread is, it might even be at next safepoint.
 733   // So we can miss this poll, but stop at next.
 734 
 735   // Load dependent store, it must not pass loading of safepoint_id.
 736   thread->safepoint_state()->set_safepoint_id(safepoint_id); // Release store
 737 
 738   // This part we can skip if we notice we miss or are in a future safepoint.
 739   OrderAccess::storestore();
 740   // Load in wait barrier should not float up
 741   thread->set_thread_state_fence(_thread_blocked);
 742 
 743   _wait_barrier->wait(static_cast<int>(safepoint_id));
 744   assert(_state != _synchronized, "Can't be");
 745 
 746   // If barrier is disarmed stop store from floating above loads in barrier.
 747   OrderAccess::loadstore();
 748   thread->set_thread_state(state);
 749 
 750   // Then we reset the safepoint id to inactive.
 751   thread->safepoint_state()->reset_safepoint_id(); // Release store
 752 
 753   OrderAccess::fence();
 754 
 755   guarantee(thread->safepoint_state()->get_safepoint_id() == InactiveSafepointCounter,
 756             "The safepoint id should be set only in block path");
 757 
 758   // cross_modify_fence is done by SafepointMechanism::process_if_requested
 759   // which is the only caller here.
 760 }
 761 
 762 // ------------------------------------------------------------------------------------------------------
 763 // Exception handlers
 764 
 765 
 766 void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
 767   assert(thread->thread_state() == _thread_in_Java, "should come from Java code");
 768   thread->set_thread_state(_thread_in_vm);
 769 
 770   // Enable WXWrite: the function is called implicitly from java code.
 771   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, thread));
 772 
 773   if (log_is_enabled(Info, safepoint, stats)) {
 774     Atomic::inc(&_nof_threads_hit_polling_page);
 775   }
 776 
 777   ThreadSafepointState* state = thread->safepoint_state();
 778 
 779   state->handle_polling_page_exception();
 780 
 781   thread->set_thread_state(_thread_in_Java);
 782 }
 783 
 784 
 785 void SafepointSynchronize::print_safepoint_timeout() {
 786   if (!timeout_error_printed) {
 787     timeout_error_printed = true;
 788     // Print out the thread info which didn't reach the safepoint for debugging
 789     // purposes (useful when there are lots of threads in the debugger).
 790     LogTarget(Warning, safepoint) lt;
 791     if (lt.is_enabled()) {
 792       ResourceMark rm;
 793       LogStream ls(lt);
 794 
 795       ls.cr();
 796       ls.print_cr("# SafepointSynchronize::begin: Timeout detected:");
 797       ls.print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint.");
 798       ls.print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:");
 799       for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur_thread = jtiwh.next(); ) {
 800         if (cur_thread->safepoint_state()->is_running()) {
 801           ls.print("# ");
 802           cur_thread->print_on(&ls);
 803           ls.cr();
 804         }
 805       }
 806       ls.print_cr("# SafepointSynchronize::begin: (End of list)");
 807     }
 808   }
 809 
 810   // To debug the long safepoint, specify both AbortVMOnSafepointTimeout &
 811   // ShowMessageBoxOnError.
 812   if (AbortVMOnSafepointTimeout && (os::elapsedTime() * MILLIUNITS > AbortVMOnSafepointTimeoutDelay)) {
 813     // Send the blocking thread a signal to terminate and write an error file.
 814     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur_thread = jtiwh.next(); ) {
 815       if (cur_thread->safepoint_state()->is_running()) {
 816         if (!os::signal_thread(cur_thread, SIGILL, "blocking a safepoint")) {
 817           break; // Could not send signal. Report fatal error.
 818         }
 819         // Give cur_thread a chance to report the error and terminate the VM.
 820         os::naked_sleep(3000);
 821       }
 822     }
 823     fatal("Safepoint sync time longer than %.6f ms detected when executing %s.",
 824           SafepointTimeoutDelay, VMThread::vm_operation()->name());
 825   }
 826 }
 827 
 828 // -------------------------------------------------------------------------------------------------------
 829 // Implementation of ThreadSafepointState
 830 
 831 ThreadSafepointState::ThreadSafepointState(JavaThread *thread)
 832   : _at_poll_safepoint(false), _thread(thread), _safepoint_safe(false),
 833     _safepoint_id(SafepointSynchronize::InactiveSafepointCounter), _next(nullptr) {
 834 }
 835 
 836 void ThreadSafepointState::create(JavaThread *thread) {
 837   ThreadSafepointState *state = new ThreadSafepointState(thread);
 838   thread->set_safepoint_state(state);
 839 }
 840 
 841 void ThreadSafepointState::destroy(JavaThread *thread) {
 842   if (thread->safepoint_state()) {
 843     delete(thread->safepoint_state());
 844     thread->set_safepoint_state(nullptr);
 845   }
 846 }
 847 
 848 uint64_t ThreadSafepointState::get_safepoint_id() const {
 849   return Atomic::load_acquire(&_safepoint_id);
 850 }
 851 
 852 void ThreadSafepointState::reset_safepoint_id() {
 853   Atomic::release_store(&_safepoint_id, SafepointSynchronize::InactiveSafepointCounter);
 854 }
 855 
 856 void ThreadSafepointState::set_safepoint_id(uint64_t safepoint_id) {
 857   Atomic::release_store(&_safepoint_id, safepoint_id);
 858 }
 859 
 860 void ThreadSafepointState::examine_state_of_thread(uint64_t safepoint_count) {
 861   assert(is_running(), "better be running or just have hit safepoint poll");
 862 
 863   JavaThreadState stable_state;
 864   if (!SafepointSynchronize::try_stable_load_state(&stable_state, _thread, safepoint_count)) {
 865     // We could not get stable state of the JavaThread.
 866     // Consider it running and just return.
 867     return;
 868   }
 869 
 870   if (safepoint_safe_with(_thread, stable_state)) {
 871     account_safe_thread();
 872     return;
 873   }
 874 
 875   // All other thread states will continue to run until they
 876   // transition and self-block in state _blocked
 877   // Safepoint polling in compiled code causes the Java threads to do the same.
 878   // Note: new threads may require a malloc so they must be allowed to finish
 879 
 880   assert(is_running(), "examine_state_of_thread on non-running thread");
 881   return;
 882 }
 883 
 884 void ThreadSafepointState::account_safe_thread() {
 885   SafepointSynchronize::decrement_waiting_to_block();
 886   if (_thread->in_critical()) {
 887     // Notice that this thread is in a critical section
 888     SafepointSynchronize::increment_jni_active_count();
 889   }
 890   DEBUG_ONLY(_thread->set_visited_for_critical_count(SafepointSynchronize::safepoint_counter());)
 891   assert(!_safepoint_safe, "Must be unsafe before safe");
 892   _safepoint_safe = true;
 893 }
 894 
 895 void ThreadSafepointState::restart() {
 896   assert(_safepoint_safe, "Must be safe before unsafe");
 897   _safepoint_safe = false;
 898 }
 899 
 900 void ThreadSafepointState::print_on(outputStream *st) const {
 901   const char *s = _safepoint_safe ? "_at_safepoint" : "_running";
 902 
 903   st->print_cr("Thread: " INTPTR_FORMAT
 904               "  [0x%2x] State: %s _at_poll_safepoint %d",
 905                p2i(_thread), _thread->osthread()->thread_id(), s, _at_poll_safepoint);
 906 
 907   _thread->print_thread_state_on(st);
 908 }
 909 
 910 // ---------------------------------------------------------------------------------------------------------------------
 911 
 912 // Process pending operation.
 913 void ThreadSafepointState::handle_polling_page_exception() {
 914   JavaThread* self = thread();
 915   assert(self == JavaThread::current(), "must be self");
 916 
 917   // Step 1: Find the nmethod from the return address
 918   address real_return_addr = self->saved_exception_pc();
 919 
 920   CodeBlob *cb = CodeCache::find_blob(real_return_addr);
 921   assert(cb != nullptr && cb->is_compiled(), "return address should be in nmethod");
 922   CompiledMethod* nm = (CompiledMethod*)cb;
 923 
 924   // Find frame of caller
 925   frame stub_fr = self->last_frame();
 926   CodeBlob* stub_cb = stub_fr.cb();
 927   assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub");
 928   RegisterMap map(self,
 929                   RegisterMap::UpdateMap::include,
 930                   RegisterMap::ProcessFrames::skip,
 931                   RegisterMap::WalkContinuation::skip);
 932   frame caller_fr = stub_fr.sender(&map);
 933 
 934   // Should only be poll_return or poll
 935   assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" );
 936 
 937   // This is a poll immediately before a return. The exception handling code
 938   // has already had the effect of causing the return to occur, so the execution
 939   // will continue immediately after the call. In addition, the oopmap at the
 940   // return point does not mark the return value as an oop (if it is), so
 941   // it needs a handle here to be updated.
 942   if( nm->is_at_poll_return(real_return_addr) ) {
 943     ResourceMark rm;
 944     // See if return type is an oop.
 945     Method* method = nm->method();
 946     bool return_oop = method->is_returning_oop();
 947     HandleMark hm(self);
 948     GrowableArray<Handle> return_values;
 949     InlineKlass* vk = nullptr;
 950     if (return_oop && InlineTypeReturnedAsFields &&
 951         (method->result_type() == T_OBJECT)) {
 952       // Check if an inline type is returned as fields
 953       vk = InlineKlass::returned_inline_klass(map);
 954       if (vk != nullptr) {
 955         // We're at a safepoint at the return of a method that returns
 956         // multiple values. We must make sure we preserve the oop values
 957         // across the safepoint.
 958         assert(vk == method->returns_inline_type(thread()), "bad inline klass");
 959         vk->save_oop_fields(map, return_values);
 960         return_oop = false;
 961       }
 962     }
 963 
 964     if (return_oop) {
 965       // The oop result has been saved on the stack together with all
 966       // the other registers. In order to preserve it over GCs we need
 967       // to keep it in a handle.
 968       oop result = caller_fr.saved_oop_result(&map);
 969       assert(oopDesc::is_oop_or_null(result), "must be oop");
 970       return_values.push(Handle(self, result));
 971       assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
 972     }
 973 
 974     // We get here if compiled return polls found a reason to call into the VM.
 975     // One condition for that is that the top frame is not yet safe to use.
 976     // The following stack watermark barrier poll will catch such situations.
 977     StackWatermarkSet::after_unwind(self);
 978 
 979     // Process pending operation
 980     SafepointMechanism::process_if_requested_with_exit_check(self, true /* check asyncs */);
 981 
 982     // restore oop result, if any
 983     if (return_oop) {
 984       assert(return_values.length() == 1, "only one return value");
 985       caller_fr.set_saved_oop_result(&map, return_values.pop()());
 986     } else if (vk != nullptr) {
 987       vk->restore_oop_results(map, return_values);
 988     }
 989   }
 990 
 991   // This is a safepoint poll. Verify the return address and block.
 992   else {
 993 
 994     // verify the blob built the "return address" correctly
 995     assert(real_return_addr == caller_fr.pc(), "must match");
 996 
 997     set_at_poll_safepoint(true);
 998     // Process pending operation
 999     // We never deliver an async exception at a polling point as the
1000     // compiler may not have an exception handler for it (polling at
1001     // a return point is ok though). We will check for a pending async
1002     // exception below and deoptimize if needed. We also cannot deoptimize
1003     // and still install the exception here because live registers needed
1004     // during deoptimization are clobbered by the exception path. The
1005     // exception will just be delivered once we get into the interpreter.
1006     SafepointMechanism::process_if_requested_with_exit_check(self, false /* check asyncs */);
1007     set_at_poll_safepoint(false);
1008 
1009     if (self->has_async_exception_condition()) {
1010       Deoptimization::deoptimize_frame(self, caller_fr.id());
1011       log_info(exceptions)("deferred async exception at compiled safepoint");
1012     }
1013 
1014     // If an exception has been installed we must verify that the top frame wasn't deoptimized.
1015     if (self->has_pending_exception() ) {
1016       RegisterMap map(self,
1017                       RegisterMap::UpdateMap::include,
1018                       RegisterMap::ProcessFrames::skip,
1019                       RegisterMap::WalkContinuation::skip);
1020       frame caller_fr = stub_fr.sender(&map);
1021       if (caller_fr.is_deoptimized_frame()) {
1022         // The exception path will destroy registers that are still
1023         // live and will be needed during deoptimization, so if we
1024         // have an exception now things are messed up. We only check
1025         // at this scope because for a poll return it is ok to deoptimize
1026         // while having a pending exception since the call we are returning
1027         // from already collides with exception handling registers and
1028         // so there is no issue (the exception handling path kills call
1029         // result registers but this is ok since the exception kills
1030         // the result anyway).
1031         fatal("Exception installed and deoptimization is pending");
1032       }
1033     }
1034   }
1035 }
1036 
1037 
1038 // -------------------------------------------------------------------------------------------------------
1039 // Implementation of SafepointTracing
1040 
1041 jlong SafepointTracing::_last_safepoint_begin_time_ns = 0;
1042 jlong SafepointTracing::_last_safepoint_sync_time_ns = 0;
1043 jlong SafepointTracing::_last_safepoint_cleanup_time_ns = 0;
1044 jlong SafepointTracing::_last_safepoint_end_time_ns = 0;
1045 jlong SafepointTracing::_last_app_time_ns = 0;
1046 int SafepointTracing::_nof_threads = 0;
1047 int SafepointTracing::_nof_running = 0;
1048 int SafepointTracing::_page_trap = 0;
1049 VM_Operation::VMOp_Type SafepointTracing::_current_type;
1050 jlong     SafepointTracing::_max_sync_time = 0;
1051 jlong     SafepointTracing::_max_cleanup_time = 0;
1052 jlong     SafepointTracing::_max_vmop_time = 0;
1053 uint64_t  SafepointTracing::_op_count[VM_Operation::VMOp_Terminating] = {0};
1054 
1055 void SafepointTracing::init() {
1056   // Application start
1057   _last_safepoint_end_time_ns = os::javaTimeNanos();
1058 }
1059 
1060 // Helper method to print the header.
1061 static void print_header(outputStream* st) {
1062   // The number of spaces is significant here, and should match the format
1063   // specifiers in print_statistics().
1064 
1065   st->print("VM Operation                 "
1066             "[ threads: total initial_running ]"
1067             "[ time:       sync    cleanup       vmop      total ]");
1068 
1069   st->print_cr(" page_trap_count");
1070 }
1071 
1072 // This prints a nice table.  To get the statistics to not shift due to the logging uptime
1073 // decorator, use the option as: -Xlog:safepoint+stats:[outputfile]:none
1074 void SafepointTracing::statistics_log() {
1075   LogTarget(Info, safepoint, stats) lt;
1076   assert (lt.is_enabled(), "should only be called when printing statistics is enabled");
1077   LogStream ls(lt);
1078 
1079   static int _cur_stat_index = 0;
1080 
1081   // Print header every 30 entries
1082   if ((_cur_stat_index % 30) == 0) {
1083     print_header(&ls);
1084     _cur_stat_index = 1;  // wrap
1085   } else {
1086     _cur_stat_index++;
1087   }
1088 
1089   ls.print("%-28s [       "
1090            INT32_FORMAT_W(8) "        " INT32_FORMAT_W(8) " "
1091            "]",
1092            VM_Operation::name(_current_type),
1093            _nof_threads,
1094            _nof_running);
1095   ls.print("[       "
1096            INT64_FORMAT_W(10) " " INT64_FORMAT_W(10) " "
1097            INT64_FORMAT_W(10) " " INT64_FORMAT_W(10) " ]",
1098            (int64_t)(_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns),
1099            (int64_t)(_last_safepoint_cleanup_time_ns - _last_safepoint_sync_time_ns),
1100            (int64_t)(_last_safepoint_end_time_ns - _last_safepoint_cleanup_time_ns),
1101            (int64_t)(_last_safepoint_end_time_ns - _last_safepoint_begin_time_ns));
1102 
1103   ls.print_cr(INT32_FORMAT_W(16), _page_trap);
1104 }
1105 
1106 // This method will be called when VM exits. This tries to summarize the sampling.
1107 // Current thread may already be deleted, so don't use ResourceMark.
1108 void SafepointTracing::statistics_exit_log() {
1109   if (!log_is_enabled(Info, safepoint, stats)) {
1110     return;
1111   }
1112   for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) {
1113     if (_op_count[index] != 0) {
1114       log_info(safepoint, stats)("%-28s" UINT64_FORMAT_W(10), VM_Operation::name(index),
1115                _op_count[index]);
1116     }
1117   }
1118 
1119   log_info(safepoint, stats)("Maximum sync time  " INT64_FORMAT" ns",
1120                               (int64_t)(_max_sync_time));
1121   log_info(safepoint, stats)("Maximum cleanup time  " INT64_FORMAT" ns",
1122                               (int64_t)(_max_cleanup_time));
1123   log_info(safepoint, stats)("Maximum vm operation time (except for Exit VM operation)  "
1124                               INT64_FORMAT " ns",
1125                               (int64_t)(_max_vmop_time));
1126 }
1127 
1128 void SafepointTracing::begin(VM_Operation::VMOp_Type type) {
1129   _op_count[type]++;
1130   _current_type = type;
1131 
1132   // update the time stamp to begin recording safepoint time
1133   _last_safepoint_begin_time_ns = os::javaTimeNanos();
1134   _last_safepoint_sync_time_ns = 0;
1135   _last_safepoint_cleanup_time_ns = 0;
1136 
1137   _last_app_time_ns = _last_safepoint_begin_time_ns - _last_safepoint_end_time_ns;
1138   _last_safepoint_end_time_ns = 0;
1139 
1140   RuntimeService::record_safepoint_begin(_last_app_time_ns);
1141 }
1142 
1143 void SafepointTracing::synchronized(int nof_threads, int nof_running, int traps) {
1144   _last_safepoint_sync_time_ns = os::javaTimeNanos();
1145   _nof_threads = nof_threads;
1146   _nof_running = nof_running;
1147   _page_trap   = traps;
1148   RuntimeService::record_safepoint_synchronized(_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns);
1149 }
1150 
1151 void SafepointTracing::cleanup() {
1152   _last_safepoint_cleanup_time_ns = os::javaTimeNanos();
1153 }
1154 
1155 void SafepointTracing::end() {
1156   _last_safepoint_end_time_ns = os::javaTimeNanos();
1157 
1158   if (_max_sync_time < (_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns)) {
1159     _max_sync_time = _last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns;
1160   }
1161   if (_max_cleanup_time < (_last_safepoint_cleanup_time_ns - _last_safepoint_sync_time_ns)) {
1162     _max_cleanup_time = _last_safepoint_cleanup_time_ns - _last_safepoint_sync_time_ns;
1163   }
1164   if (_max_vmop_time < (_last_safepoint_end_time_ns - _last_safepoint_sync_time_ns)) {
1165     _max_vmop_time = _last_safepoint_end_time_ns - _last_safepoint_sync_time_ns;
1166   }
1167   if (log_is_enabled(Info, safepoint, stats)) {
1168     statistics_log();
1169   }
1170 
1171   log_info(safepoint)(
1172      "Safepoint \"%s\", "
1173      "Time since last: " JLONG_FORMAT " ns, "
1174      "Reaching safepoint: " JLONG_FORMAT " ns, "
1175      "Cleanup: " JLONG_FORMAT " ns, "
1176      "At safepoint: " JLONG_FORMAT " ns, "
1177      "Total: " JLONG_FORMAT " ns",
1178       VM_Operation::name(_current_type),
1179       _last_app_time_ns,
1180       _last_safepoint_sync_time_ns    - _last_safepoint_begin_time_ns,
1181       _last_safepoint_cleanup_time_ns - _last_safepoint_sync_time_ns,
1182       _last_safepoint_end_time_ns     - _last_safepoint_cleanup_time_ns,
1183       _last_safepoint_end_time_ns     - _last_safepoint_begin_time_ns
1184      );
1185 
1186   RuntimeService::record_safepoint_end(_last_safepoint_end_time_ns - _last_safepoint_sync_time_ns);
1187 }