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