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