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