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