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