1 /*
   2  * Copyright (c) 1997, 2019, 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 "classfile/classLoaderDataGraph.inline.hpp"
  27 #include "classfile/dictionary.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/icBuffer.hpp"
  33 #include "code/nmethod.hpp"
  34 #include "code/pcDesc.hpp"
  35 #include "code/scopeDesc.hpp"
  36 #include "gc/shared/collectedHeap.hpp"
  37 #include "gc/shared/gcLocker.hpp"
  38 #include "gc/shared/oopStorage.hpp"
  39 #include "gc/shared/strongRootsScope.hpp"
  40 #include "gc/shared/workgroup.hpp"
  41 #include "interpreter/interpreter.hpp"
  42 #include "jfr/jfrEvents.hpp"
  43 #include "logging/log.hpp"
  44 #include "logging/logStream.hpp"
  45 #include "memory/resourceArea.hpp"
  46 #include "memory/universe.hpp"
  47 #include "oops/oop.inline.hpp"
  48 #include "oops/symbol.hpp"
  49 #include "runtime/atomic.hpp"
  50 #include "runtime/compilationPolicy.hpp"
  51 #include "runtime/continuation.hpp"
  52 #include "runtime/deoptimization.hpp"
  53 #include "runtime/frame.inline.hpp"
  54 #include "runtime/handles.inline.hpp"
  55 #include "runtime/interfaceSupport.inline.hpp"
  56 #include "runtime/mutexLocker.hpp"
  57 #include "runtime/orderAccess.hpp"
  58 #include "runtime/osThread.hpp"
  59 #include "runtime/safepoint.hpp"
  60 #include "runtime/safepointMechanism.inline.hpp"
  61 #include "runtime/signature.hpp"
  62 #include "runtime/stubCodeGenerator.hpp"
  63 #include "runtime/stubRoutines.hpp"
  64 #include "runtime/sweeper.hpp"
  65 #include "runtime/synchronizer.hpp"
  66 #include "runtime/thread.inline.hpp"
  67 #include "runtime/threadSMR.hpp"
  68 #include "runtime/timerTrace.hpp"
  69 #include "services/runtimeService.hpp"
  70 #include "utilities/events.hpp"
  71 #include "utilities/macros.hpp"
  72 
  73 static void post_safepoint_begin_event(EventSafepointBegin& event,
  74                                        uint64_t safepoint_id,
  75                                        int thread_count,
  76                                        int critical_thread_count) {
  77   if (event.should_commit()) {
  78     event.set_safepointId(safepoint_id);
  79     event.set_totalThreadCount(thread_count);
  80     event.set_jniCriticalThreadCount(critical_thread_count);
  81     event.commit();
  82   }
  83 }
  84 
  85 static void post_safepoint_cleanup_event(EventSafepointCleanup& event, uint64_t safepoint_id) {
  86   if (event.should_commit()) {
  87     event.set_safepointId(safepoint_id);
  88     event.commit();
  89   }
  90 }
  91 
  92 static void post_safepoint_synchronize_event(EventSafepointStateSynchronization& event,
  93                                              uint64_t safepoint_id,
  94                                              int initial_number_of_threads,
  95                                              int threads_waiting_to_block,
  96                                              uint64_t iterations) {
  97   if (event.should_commit()) {
  98     event.set_safepointId(safepoint_id);
  99     event.set_initialThreadCount(initial_number_of_threads);
 100     event.set_runningThreadCount(threads_waiting_to_block);
 101     event.set_iterations(iterations);
 102     event.commit();
 103   }
 104 }
 105 
 106 static void post_safepoint_cleanup_task_event(EventSafepointCleanupTask& event,
 107                                               uint64_t safepoint_id,
 108                                               const char* name) {
 109   if (event.should_commit()) {
 110     event.set_safepointId(safepoint_id);
 111     event.set_name(name);
 112     event.commit();
 113   }
 114 }
 115 
 116 static void post_safepoint_end_event(EventSafepointEnd& event, uint64_t safepoint_id) {
 117   if (event.should_commit()) {
 118     event.set_safepointId(safepoint_id);
 119     event.commit();
 120   }
 121 }
 122 
 123 // SafepointCheck
 124 SafepointStateTracker::SafepointStateTracker(uint64_t safepoint_id, bool at_safepoint)
 125   : _safepoint_id(safepoint_id), _at_safepoint(at_safepoint) {}
 126 
 127 bool SafepointStateTracker::safepoint_state_changed() {
 128   return _safepoint_id != SafepointSynchronize::safepoint_id() ||
 129     _at_safepoint != SafepointSynchronize::is_at_safepoint();
 130 }
 131 
 132 // --------------------------------------------------------------------------------------------------
 133 // Implementation of Safepoint begin/end
 134 
 135 SafepointSynchronize::SynchronizeState volatile SafepointSynchronize::_state = SafepointSynchronize::_not_synchronized;
 136 int SafepointSynchronize::_waiting_to_block = 0;
 137 volatile uint64_t SafepointSynchronize::_safepoint_counter = 0;
 138 uint64_t SafepointSynchronize::_safepoint_id = 0;
 139 const uint64_t SafepointSynchronize::InactiveSafepointCounter = 0;
 140 int SafepointSynchronize::_current_jni_active_count = 0;
 141 
 142 WaitBarrier* SafepointSynchronize::_wait_barrier;
 143 
 144 static volatile bool PageArmed = false;        // safepoint polling page is RO|RW vs PROT_NONE
 145 static bool timeout_error_printed = false;
 146 
 147 // Statistic related
 148 static jlong _safepoint_begin_time = 0;
 149 static volatile int _nof_threads_hit_polling_page = 0;
 150 
 151 void SafepointSynchronize::init(Thread* vmthread) {
 152   // WaitBarrier should never be destroyed since we will have
 153   // threads waiting on it while exiting.
 154   _wait_barrier = new WaitBarrier(vmthread);
 155   SafepointTracing::init();
 156 }
 157 
 158 void SafepointSynchronize::increment_jni_active_count() {
 159   assert(Thread::current()->is_VM_thread(), "Only VM thread may increment");
 160   ++_current_jni_active_count;
 161 }
 162 
 163 void SafepointSynchronize::decrement_waiting_to_block() {
 164   assert(_waiting_to_block > 0, "sanity check");
 165   assert(Thread::current()->is_VM_thread(), "Only VM thread may decrement");
 166   --_waiting_to_block;
 167 }
 168 
 169 bool SafepointSynchronize::thread_not_running(ThreadSafepointState *cur_state) {
 170   if (!cur_state->is_running()) {
 171     return true;
 172   }
 173   cur_state->examine_state_of_thread(SafepointSynchronize::safepoint_counter());
 174   if (!cur_state->is_running()) {
 175     return true;
 176   }
 177   LogTarget(Trace, safepoint) lt;
 178   if (lt.is_enabled()) {
 179     ResourceMark rm;
 180     LogStream ls(lt);
 181     cur_state->print_on(&ls);
 182   }
 183   return false;
 184 }
 185 
 186 #ifdef ASSERT
 187 static void assert_list_is_valid(const ThreadSafepointState* tss_head, int still_running) {
 188   int a = 0;
 189   const ThreadSafepointState *tmp_tss = tss_head;
 190   while (tmp_tss != NULL) {
 191     ++a;
 192     assert(tmp_tss->is_running(), "Illegal initial state");
 193     tmp_tss = tmp_tss->get_next();
 194   }
 195   assert(a == still_running, "Must be the same");
 196 }
 197 #endif // ASSERT
 198 
 199 static void back_off(int64_t start_time) {
 200   // We start with fine-grained nanosleeping until a millisecond has
 201   // passed, at which point we resort to plain naked_short_sleep.
 202   if (os::javaTimeNanos() - start_time < NANOSECS_PER_MILLISEC) {
 203     os::naked_short_nanosleep(10 * (NANOUNITS / MICROUNITS));
 204   } else {
 205     os::naked_short_sleep(1);
 206   }
 207 }
 208 
 209 int SafepointSynchronize::synchronize_threads(jlong safepoint_limit_time, int nof_threads, int* initial_running)
 210 {
 211   JavaThreadIteratorWithHandle jtiwh;
 212 
 213 #ifdef ASSERT
 214   for (; JavaThread *cur = jtiwh.next(); ) {
 215     assert(cur->safepoint_state()->is_running(), "Illegal initial state");
 216   }
 217   jtiwh.rewind();
 218 #endif // ASSERT
 219 
 220   // Iterate through all threads until it has been determined how to stop them all at a safepoint.
 221   int still_running = nof_threads;
 222   ThreadSafepointState *tss_head = NULL;
 223   ThreadSafepointState **p_prev = &tss_head;
 224   for (; JavaThread *cur = jtiwh.next(); ) {
 225     ThreadSafepointState *cur_tss = cur->safepoint_state();
 226     assert(cur_tss->get_next() == NULL, "Must be NULL");
 227     if (thread_not_running(cur_tss)) {
 228       --still_running;
 229     } else {
 230       *p_prev = cur_tss;
 231       p_prev = cur_tss->next_ptr();
 232     }
 233   }
 234   *p_prev = NULL;
 235 
 236   DEBUG_ONLY(assert_list_is_valid(tss_head, still_running);)
 237 
 238   *initial_running = still_running;
 239 
 240   // If there is no thread still running, we are already done.
 241   if (still_running <= 0) {
 242     assert(tss_head == NULL, "Must be empty");
 243     return 1;
 244   }
 245 
 246   int iterations = 1; // The first iteration is above.
 247   int64_t start_time = os::javaTimeNanos();
 248 
 249   do {
 250     // Check if this has taken too long:
 251     if (SafepointTimeout && safepoint_limit_time < os::javaTimeNanos()) {
 252       print_safepoint_timeout();
 253     }
 254     if (int(iterations) == -1) { // overflow - something is wrong.
 255       // We can only overflow here when we are using global
 256       // polling pages. We keep this guarantee in its original
 257       // form so that searches of the bug database for this
 258       // failure mode find the right bugs.
 259       guarantee (!PageArmed, "invariant");
 260     }
 261 
 262     p_prev = &tss_head;
 263     ThreadSafepointState *cur_tss = tss_head;
 264     while (cur_tss != NULL) {
 265       assert(cur_tss->is_running(), "Illegal initial state");
 266       if (thread_not_running(cur_tss)) {
 267         --still_running;
 268         *p_prev = NULL;
 269         ThreadSafepointState *tmp = cur_tss;
 270         cur_tss = cur_tss->get_next();
 271         tmp->set_next(NULL);
 272       } else {
 273         *p_prev = cur_tss;
 274         p_prev = cur_tss->next_ptr();
 275         cur_tss = cur_tss->get_next();
 276       }
 277     }
 278 
 279     DEBUG_ONLY(assert_list_is_valid(tss_head, still_running);)
 280 
 281     if (still_running > 0) {
 282       back_off(start_time);
 283     }
 284 
 285     iterations++;
 286   } while (still_running > 0);
 287 
 288   assert(tss_head == NULL, "Must be empty");
 289 
 290   return iterations;
 291 }
 292 
 293 void SafepointSynchronize::arm_safepoint() {
 294   // Begin the process of bringing the system to a safepoint.
 295   // Java threads can be in several different states and are
 296   // stopped by different mechanisms:
 297   //
 298   //  1. Running interpreted
 299   //     When executing branching/returning byte codes interpreter
 300   //     checks if the poll is armed, if so blocks in SS::block().
 301   //     When using global polling the interpreter dispatch table
 302   //     is changed to force it to check for a safepoint condition
 303   //     between bytecodes.
 304   //  2. Running in native code
 305   //     When returning from the native code, a Java thread must check
 306   //     the safepoint _state to see if we must block.  If the
 307   //     VM thread sees a Java thread in native, it does
 308   //     not wait for this thread to block.  The order of the memory
 309   //     writes and reads of both the safepoint state and the Java
 310   //     threads state is critical.  In order to guarantee that the
 311   //     memory writes are serialized with respect to each other,
 312   //     the VM thread issues a memory barrier instruction.
 313   //  3. Running compiled Code
 314   //     Compiled code reads the local polling page that
 315   //     is set to fault if we are trying to get to a safepoint.
 316   //  4. Blocked
 317   //     A thread which is blocked will not be allowed to return from the
 318   //     block condition until the safepoint operation is complete.
 319   //  5. In VM or Transitioning between states
 320   //     If a Java thread is currently running in the VM or transitioning
 321   //     between states, the safepointing code will poll the thread state
 322   //     until the thread blocks itself when it attempts transitions to a
 323   //     new state or locking a safepoint checked monitor.
 324 
 325   // We must never miss a thread with correct safepoint id, so we must make sure we arm
 326   // the wait barrier for the next safepoint id/counter.
 327   // Arming must be done after resetting _current_jni_active_count, _waiting_to_block.
 328   _wait_barrier->arm(static_cast<int>(_safepoint_counter + 1));
 329 
 330   assert((_safepoint_counter & 0x1) == 0, "must be even");
 331   // The store to _safepoint_counter must happen after any stores in arming.
 332   OrderAccess::release_store(&_safepoint_counter, _safepoint_counter + 1);
 333 
 334   // We are synchronizing
 335   OrderAccess::storestore(); // Ordered with _safepoint_counter
 336   _state = _synchronizing;
 337 
 338   if (SafepointMechanism::uses_thread_local_poll()) {
 339     // Arming the per thread poll while having _state != _not_synchronized means safepointing
 340     log_trace(safepoint)("Setting thread local yield flag for threads");
 341     OrderAccess::storestore(); // storestore, global state -> local state
 342     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur = jtiwh.next(); ) {
 343       // Make sure the threads start polling, it is time to yield.
 344       SafepointMechanism::arm_local_poll(cur);
 345     }
 346   }
 347   OrderAccess::fence(); // storestore|storeload, global state -> local state
 348 
 349   if (SafepointMechanism::uses_global_page_poll()) {
 350     // Make interpreter safepoint aware
 351     Interpreter::notice_safepoints();
 352 
 353     // Make polling safepoint aware
 354     guarantee (!PageArmed, "invariant") ;
 355     PageArmed = true;
 356     os::make_polling_page_unreadable();
 357   }
 358 }
 359 
 360 // Roll all threads forward to a safepoint and suspend them all
 361 void SafepointSynchronize::begin() {
 362   assert(Thread::current()->is_VM_thread(), "Only VM thread may execute a safepoint");
 363 
 364   EventSafepointBegin begin_event;
 365   SafepointTracing::begin(VMThread::vm_op_type());
 366 
 367   Universe::heap()->safepoint_synchronize_begin();
 368 
 369   // By getting the Threads_lock, we assure that no threads are about to start or
 370   // exit. It is released again in SafepointSynchronize::end().
 371   Threads_lock->lock();
 372 
 373   assert( _state == _not_synchronized, "trying to safepoint synchronize with wrong state");
 374 
 375   int nof_threads = Threads::number_of_threads();
 376 
 377   _nof_threads_hit_polling_page = 0;
 378 
 379   log_debug(safepoint)("Safepoint synchronization initiated using %s wait barrier. (%d threads)", _wait_barrier->description(), nof_threads);
 380 
 381   // Reset the count of active JNI critical threads
 382   _current_jni_active_count = 0;
 383 
 384   // Set number of threads to wait for
 385   _waiting_to_block = nof_threads;
 386 
 387   jlong safepoint_limit_time = 0;
 388   if (SafepointTimeout) {
 389     // Set the limit time, so that it can be compared to see if this has taken
 390     // too long to complete.
 391     safepoint_limit_time = SafepointTracing::start_of_safepoint() + (jlong)SafepointTimeoutDelay * (NANOUNITS / MILLIUNITS);
 392     timeout_error_printed = false;
 393   }
 394 
 395   EventSafepointStateSynchronization sync_event;
 396   int initial_running = 0;
 397 
 398   // Arms the safepoint, _current_jni_active_count and _waiting_to_block must be set before.
 399   arm_safepoint();
 400 
 401   // Will spin until all threads are safe.
 402   int iterations = synchronize_threads(safepoint_limit_time, nof_threads, &initial_running);
 403   assert(_waiting_to_block == 0, "No thread should be running");
 404 
 405 #ifndef PRODUCT
 406   if (safepoint_limit_time != 0) {
 407     jlong current_time = os::javaTimeNanos();
 408     if (safepoint_limit_time < current_time) {
 409       log_warning(safepoint)("# SafepointSynchronize: Finished after "
 410                     INT64_FORMAT_W(6) " ms",
 411                     (int64_t)(current_time - SafepointTracing::start_of_safepoint()) / (NANOUNITS / MILLIUNITS));
 412     }
 413   }
 414 #endif
 415 
 416   assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
 417 
 418   // Record state
 419   _state = _synchronized;
 420 
 421   OrderAccess::fence();
 422 
 423   // Set the new id
 424   ++_safepoint_id;
 425 
 426 #ifdef ASSERT
 427   // Make sure all the threads were visited.
 428   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur = jtiwh.next(); ) {
 429     assert(cur->was_visited_for_critical_count(_safepoint_counter), "missed a thread");
 430   }
 431 #endif // ASSERT
 432 
 433   // Update the count of active JNI critical regions
 434   GCLocker::set_jni_lock_count(_current_jni_active_count);
 435 
 436   post_safepoint_synchronize_event(sync_event,
 437                                    _safepoint_id,
 438                                    initial_running,
 439                                    _waiting_to_block, iterations);
 440 
 441   SafepointTracing::synchronized(nof_threads, initial_running, _nof_threads_hit_polling_page);
 442 
 443   // We do the safepoint cleanup first since a GC related safepoint
 444   // needs cleanup to be completed before running the GC op.
 445   EventSafepointCleanup cleanup_event;
 446   do_cleanup_tasks();
 447   post_safepoint_cleanup_event(cleanup_event, _safepoint_id);
 448 
 449   post_safepoint_begin_event(begin_event, _safepoint_id, nof_threads, _current_jni_active_count);
 450   SafepointTracing::cleanup();
 451 }
 452 
 453 void SafepointSynchronize::disarm_safepoint() {
 454   uint64_t active_safepoint_counter = _safepoint_counter;
 455   {
 456     JavaThreadIteratorWithHandle jtiwh;
 457 #ifdef ASSERT
 458     // A pending_exception cannot be installed during a safepoint.  The threads
 459     // may install an async exception after they come back from a safepoint into
 460     // pending_exception after they unblock.  But that should happen later.
 461     for (; JavaThread *cur = jtiwh.next(); ) {
 462       assert (!(cur->has_pending_exception() &&
 463                 cur->safepoint_state()->is_at_poll_safepoint()),
 464               "safepoint installed a pending exception");
 465     }
 466 #endif // ASSERT
 467 
 468     if (SafepointMechanism::uses_global_page_poll()) {
 469       guarantee (PageArmed, "invariant");
 470       // Make polling safepoint aware
 471       os::make_polling_page_readable();
 472       PageArmed = false;
 473       // Remove safepoint check from interpreter
 474       Interpreter::ignore_safepoints();
 475     }
 476 
 477     OrderAccess::fence(); // keep read and write of _state from floating up
 478     assert(_state == _synchronized, "must be synchronized before ending safepoint synchronization");
 479 
 480     // Change state first to _not_synchronized.
 481     // No threads should see _synchronized when running.
 482     _state = _not_synchronized;
 483 
 484     // Set the next dormant (even) safepoint id.
 485     assert((_safepoint_counter & 0x1) == 1, "must be odd");
 486     OrderAccess::release_store(&_safepoint_counter, _safepoint_counter + 1);
 487 
 488     OrderAccess::fence(); // Keep the local state from floating up.
 489 
 490     jtiwh.rewind();
 491     for (; JavaThread *current = jtiwh.next(); ) {
 492       // Clear the visited flag to ensure that the critical counts are collected properly.
 493       DEBUG_ONLY(current->reset_visited_for_critical_count(active_safepoint_counter);)
 494       ThreadSafepointState* cur_state = current->safepoint_state();
 495       assert(!cur_state->is_running(), "Thread not suspended at safepoint");
 496       cur_state->restart(); // TSS _running
 497       assert(cur_state->is_running(), "safepoint state has not been reset");
 498 
 499       SafepointMechanism::disarm_if_needed(current, false /* NO release */);
 500     }
 501   } // ~JavaThreadIteratorWithHandle
 502 
 503   // Release threads lock, so threads can be created/destroyed again.
 504   Threads_lock->unlock();
 505 
 506   // Wake threads after local state is correctly set.
 507   _wait_barrier->disarm();
 508 }
 509 
 510 // Wake up all threads, so they are ready to resume execution after the safepoint
 511 // operation has been carried out
 512 void SafepointSynchronize::end() {
 513   assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
 514   EventSafepointEnd event;
 515   assert(Thread::current()->is_VM_thread(), "Only VM thread can execute a safepoint");
 516 
 517   disarm_safepoint();
 518 
 519   Universe::heap()->safepoint_synchronize_end();
 520 
 521   SafepointTracing::end();
 522 
 523   post_safepoint_end_event(event, safepoint_id());
 524 }
 525 
 526 bool SafepointSynchronize::is_cleanup_needed() {
 527   // Need a safepoint if there are many monitors to deflate.
 528   if (ObjectSynchronizer::is_cleanup_needed()) return true;
 529   // Need a safepoint if some inline cache buffers is non-empty
 530   if (!InlineCacheBuffer::is_empty()) return true;
 531   if (StringTable::needs_rehashing()) return true;
 532   if (SymbolTable::needs_rehashing()) return true;
 533   return false;
 534 }
 535 
 536 class ParallelSPCleanupThreadClosure : public ThreadClosure {
 537 private:
 538   CodeBlobClosure* _nmethod_cl;
 539   DeflateMonitorCounters* _counters;
 540 
 541 public:
 542   ParallelSPCleanupThreadClosure(DeflateMonitorCounters* counters) :
 543     _nmethod_cl(UseCodeAging ? NMethodSweeper::prepare_reset_hotness_counters() : NULL),
 544     _counters(counters) {}
 545 
 546   void do_thread(Thread* thread) {
 547     ObjectSynchronizer::deflate_thread_local_monitors(thread, _counters);
 548     if (_nmethod_cl != NULL && thread->is_Java_thread() &&
 549         ! thread->is_Code_cache_sweeper_thread()) {
 550       JavaThread* jt = (JavaThread*) thread;
 551       jt->nmethods_do(_nmethod_cl);
 552     }
 553   }
 554 };
 555 
 556 class ParallelSPCleanupTask : public AbstractGangTask {
 557 private:
 558   SubTasksDone _subtasks;
 559   ParallelSPCleanupThreadClosure _cleanup_threads_cl;
 560   uint _num_workers;
 561   DeflateMonitorCounters* _counters;
 562 public:
 563   ParallelSPCleanupTask(uint num_workers, DeflateMonitorCounters* counters) :
 564     AbstractGangTask("Parallel Safepoint Cleanup"),
 565     _subtasks(SubTasksDone(SafepointSynchronize::SAFEPOINT_CLEANUP_NUM_TASKS)),
 566     _cleanup_threads_cl(ParallelSPCleanupThreadClosure(counters)),
 567     _num_workers(num_workers),
 568     _counters(counters) {}
 569 
 570   void work(uint worker_id) {
 571     uint64_t safepoint_id = SafepointSynchronize::safepoint_id();
 572     // All threads deflate monitors and mark nmethods (if necessary).
 573     Threads::possibly_parallel_threads_do(true, &_cleanup_threads_cl);
 574 
 575     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_DEFLATE_MONITORS)) {
 576       const char* name = "deflating global idle monitors";
 577       EventSafepointCleanupTask event;
 578       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 579       ObjectSynchronizer::deflate_idle_monitors(_counters);
 580 
 581       post_safepoint_cleanup_task_event(event, safepoint_id, name);
 582     }
 583 
 584     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_UPDATE_INLINE_CACHES)) {
 585       const char* name = "updating inline caches";
 586       EventSafepointCleanupTask event;
 587       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 588       InlineCacheBuffer::update_inline_caches();
 589 
 590       post_safepoint_cleanup_task_event(event, safepoint_id, name);
 591     }
 592 
 593     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_COMPILATION_POLICY)) {
 594       const char* name = "compilation policy safepoint handler";
 595       EventSafepointCleanupTask event;
 596       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 597       CompilationPolicy::policy()->do_safepoint_work();
 598 
 599       post_safepoint_cleanup_task_event(event, safepoint_id, name);
 600     }
 601 
 602     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_SYMBOL_TABLE_REHASH)) {
 603       if (SymbolTable::needs_rehashing()) {
 604         const char* name = "rehashing symbol table";
 605         EventSafepointCleanupTask event;
 606         TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 607         SymbolTable::rehash_table();
 608 
 609         post_safepoint_cleanup_task_event(event, safepoint_id, name);
 610       }
 611     }
 612 
 613     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_STRING_TABLE_REHASH)) {
 614       if (StringTable::needs_rehashing()) {
 615         const char* name = "rehashing string table";
 616         EventSafepointCleanupTask event;
 617         TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 618         StringTable::rehash_table();
 619 
 620         post_safepoint_cleanup_task_event(event, safepoint_id, name);
 621       }
 622     }
 623 
 624     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_CLD_PURGE)) {
 625       if (ClassLoaderDataGraph::should_purge_and_reset()) {
 626         // CMS delays purging the CLDG until the beginning of the next safepoint and to
 627         // make sure concurrent sweep is done
 628         const char* name = "purging class loader data graph";
 629         EventSafepointCleanupTask event;
 630         TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 631         ClassLoaderDataGraph::purge();
 632 
 633         post_safepoint_cleanup_task_event(event, safepoint_id, name);
 634       }
 635     }
 636 
 637     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_SYSTEM_DICTIONARY_RESIZE)) {
 638       if (Dictionary::does_any_dictionary_needs_resizing()) {
 639         const char* name = "resizing system dictionaries";
 640         EventSafepointCleanupTask event;
 641         TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 642         ClassLoaderDataGraph::resize_dictionaries();
 643 
 644         post_safepoint_cleanup_task_event(event, safepoint_id, name);
 645       }
 646     }
 647 
 648     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_REQUEST_OOPSTORAGE_CLEANUP)) {
 649       // Don't bother reporting event or time for this very short operation.
 650       // To have any utility we'd also want to report whether needed.
 651       OopStorage::trigger_cleanup_if_needed();
 652     }
 653 
 654    if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_KEEPALIVES)) {
 655      const char* name = "cleaning keepalive jweak handles";
 656      EventSafepointCleanupTask event;
 657      TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 658      Continuations::cleanup_keepalives();
 659 
 660      post_safepoint_cleanup_task_event(event, safepoint_id, name);
 661    }
 662 
 663     _subtasks.all_tasks_completed(_num_workers);
 664   }
 665 };
 666 
 667 // Various cleaning tasks that should be done periodically at safepoints.
 668 void SafepointSynchronize::do_cleanup_tasks() {
 669 
 670   TraceTime timer("safepoint cleanup tasks", TRACETIME_LOG(Info, safepoint, cleanup));
 671 
 672   // Prepare for monitor deflation.
 673   DeflateMonitorCounters deflate_counters;
 674   ObjectSynchronizer::prepare_deflate_idle_monitors(&deflate_counters);
 675 
 676   CollectedHeap* heap = Universe::heap();
 677   assert(heap != NULL, "heap not initialized yet?");
 678   WorkGang* cleanup_workers = heap->get_safepoint_workers();
 679   if (cleanup_workers != NULL) {
 680     // Parallel cleanup using GC provided thread pool.
 681     uint num_cleanup_workers = cleanup_workers->active_workers();
 682     ParallelSPCleanupTask cleanup(num_cleanup_workers, &deflate_counters);
 683     StrongRootsScope srs(num_cleanup_workers);
 684     cleanup_workers->run_task(&cleanup);
 685   } else {
 686     // Serial cleanup using VMThread.
 687     ParallelSPCleanupTask cleanup(1, &deflate_counters);
 688     StrongRootsScope srs(1);
 689     cleanup.work(0);
 690   }
 691 
 692   // Needs to be done single threaded by the VMThread.  This walks
 693   // the thread stacks looking for references to metadata before
 694   // deciding to remove it from the metaspaces.
 695   if (ClassLoaderDataGraph::should_clean_metaspaces_and_reset()) {
 696     const char* name = "cleanup live ClassLoaderData metaspaces";
 697     TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 698     ClassLoaderDataGraph::walk_metadata_and_clean_metaspaces();
 699   }
 700 
 701   // Finish monitor deflation.
 702   ObjectSynchronizer::finish_deflate_idle_monitors(&deflate_counters);
 703 
 704   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
 705 }
 706 
 707 // Methods for determining if a JavaThread is safepoint safe.
 708 
 709 // False means unsafe with undetermined state.
 710 // True means a determined state, but it may be an unsafe state.
 711 // If called from a non-safepoint context safepoint_count MUST be InactiveSafepointCounter.
 712 bool SafepointSynchronize::try_stable_load_state(JavaThreadState *state, JavaThread *thread, uint64_t safepoint_count) {
 713   assert((safepoint_count != InactiveSafepointCounter &&
 714           Thread::current() == (Thread*)VMThread::vm_thread() &&
 715           SafepointSynchronize::_state != _not_synchronized)
 716          || safepoint_count == InactiveSafepointCounter, "Invalid check");
 717 
 718   // To handle the thread_blocked state on the backedge of the WaitBarrier from
 719   // previous safepoint and reading the reset value (0/InactiveSafepointCounter) we
 720   // re-read state after we read thread safepoint id. The JavaThread changes its
 721   // thread state from thread_blocked before resetting safepoint id to 0.
 722   // This guarantees the second read will be from an updated thread state. It can
 723   // either be different state making this an unsafe state or it can see blocked
 724   // again. When we see blocked twice with a 0 safepoint id, either:
 725   // - It is normally blocked, e.g. on Mutex, TBIVM.
 726   // - It was in SS:block(), looped around to SS:block() and is blocked on the WaitBarrier.
 727   // - It was in SS:block() but now on a Mutex.
 728   // All of these cases are safe.
 729 
 730   *state = thread->thread_state();
 731   OrderAccess::loadload();
 732   uint64_t sid = thread->safepoint_state()->get_safepoint_id();  // Load acquire
 733   if (sid != InactiveSafepointCounter && sid != safepoint_count) {
 734     // In an old safepoint, state not relevant.
 735     return false;
 736   }
 737   return *state == thread->thread_state();
 738 }
 739 
 740 static bool safepoint_safe_with(JavaThread *thread, JavaThreadState state) {
 741   switch(state) {
 742   case _thread_in_native:
 743     // native threads are safe if they have no java stack or have walkable stack
 744     return !thread->has_last_Java_frame() || thread->frame_anchor()->walkable();
 745 
 746   case _thread_blocked:
 747     // On wait_barrier or blocked.
 748     // Blocked threads should already have walkable stack.
 749     assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "blocked and not walkable");
 750     return true;
 751 
 752   default:
 753     return false;
 754   }
 755 }
 756 
 757 bool SafepointSynchronize::handshake_safe(JavaThread *thread) {
 758   // This function must be called with the Threads_lock held so an externally
 759   // suspended thread cannot be resumed thus it is safe.
 760   assert(Threads_lock->owned_by_self() && Thread::current()->is_VM_thread(),
 761          "Must hold Threads_lock and be VMThread");
 762   if (thread->is_ext_suspended() || thread->is_terminated()) {
 763     return true;
 764   }
 765   JavaThreadState stable_state;
 766   if (try_stable_load_state(&stable_state, thread, InactiveSafepointCounter)) {
 767     return safepoint_safe_with(thread, stable_state);
 768   }
 769   return false;
 770 }
 771 
 772 // See if the thread is running inside a lazy critical native and
 773 // update the thread critical count if so.  Also set a suspend flag to
 774 // cause the native wrapper to return into the JVM to do the unlock
 775 // once the native finishes.
 776 static void check_for_lazy_critical_native(JavaThread *thread, JavaThreadState state) {
 777   if (state == _thread_in_native &&
 778       thread->has_last_Java_frame() &&
 779       thread->frame_anchor()->walkable()) {
 780     // This thread might be in a critical native nmethod so look at
 781     // the top of the stack and increment the critical count if it
 782     // is.
 783     frame wrapper_frame = thread->last_frame();
 784     CodeBlob* stub_cb = wrapper_frame.cb();
 785     if (stub_cb != NULL &&
 786         stub_cb->is_nmethod() &&
 787         stub_cb->as_nmethod_or_null()->is_lazy_critical_native()) {
 788       // A thread could potentially be in a critical native across
 789       // more than one safepoint, so only update the critical state on
 790       // the first one.  When it returns it will perform the unlock.
 791       if (!thread->do_critical_native_unlock()) {
 792 #ifdef ASSERT
 793         if (!thread->in_critical()) {
 794           GCLocker::increment_debug_jni_lock_count();
 795         }
 796 #endif
 797         thread->enter_critical();
 798         // Make sure the native wrapper calls back on return to
 799         // perform the needed critical unlock.
 800         thread->set_critical_native_unlock();
 801       }
 802     }
 803   }
 804 }
 805 
 806 // -------------------------------------------------------------------------------------------------------
 807 // Implementation of Safepoint blocking point
 808 
 809 void SafepointSynchronize::block(JavaThread *thread) {
 810   assert(thread != NULL, "thread must be set");
 811   assert(thread->is_Java_thread(), "not a Java thread");
 812 
 813   // Threads shouldn't block if they are in the middle of printing, but...
 814   ttyLocker::break_tty_lock_for_safepoint(os::current_thread_id());
 815 
 816   // Only bail from the block() call if the thread is gone from the
 817   // thread list; starting to exit should still block.
 818   if (thread->is_terminated()) {
 819      // block current thread if we come here from native code when VM is gone
 820      thread->block_if_vm_exited();
 821 
 822      // otherwise do nothing
 823      return;
 824   }
 825 
 826   JavaThreadState state = thread->thread_state();
 827   thread->frame_anchor()->make_walkable(thread);
 828 
 829   uint64_t safepoint_id = SafepointSynchronize::safepoint_counter();
 830   // Check that we have a valid thread_state at this point
 831   switch(state) {
 832     case _thread_in_vm_trans:
 833     case _thread_in_Java:        // From compiled code
 834     case _thread_in_native_trans:
 835     case _thread_blocked_trans:
 836     case _thread_new_trans:
 837 
 838       // We have no idea where the VMThread is, it might even be at next safepoint.
 839       // So we can miss this poll, but stop at next.
 840 
 841       // Load dependent store, it must not pass loading of safepoint_id.
 842       thread->safepoint_state()->set_safepoint_id(safepoint_id); // Release store
 843 
 844       // This part we can skip if we notice we miss or are in a future safepoint.
 845       OrderAccess::storestore();
 846       // Load in wait barrier should not float up
 847       thread->set_thread_state_fence(_thread_blocked);
 848 
 849       _wait_barrier->wait(static_cast<int>(safepoint_id));
 850       assert(_state != _synchronized, "Can't be");
 851 
 852       // If barrier is disarmed stop store from floating above loads in barrier.
 853       OrderAccess::loadstore();
 854       thread->set_thread_state(state);
 855 
 856       // Then we reset the safepoint id to inactive.
 857       thread->safepoint_state()->reset_safepoint_id(); // Release store
 858 
 859       OrderAccess::fence();
 860 
 861       break;
 862 
 863     default:
 864      fatal("Illegal threadstate encountered: %d", state);
 865   }
 866   guarantee(thread->safepoint_state()->get_safepoint_id() == InactiveSafepointCounter,
 867             "The safepoint id should be set only in block path");
 868 
 869   // Check for pending. async. exceptions or suspends - except if the
 870   // thread was blocked inside the VM. has_special_runtime_exit_condition()
 871   // is called last since it grabs a lock and we only want to do that when
 872   // we must.
 873   //
 874   // Note: we never deliver an async exception at a polling point as the
 875   // compiler may not have an exception handler for it. The polling
 876   // code will notice the async and deoptimize and the exception will
 877   // be delivered. (Polling at a return point is ok though). Sure is
 878   // a lot of bother for a deprecated feature...
 879   //
 880   // We don't deliver an async exception if the thread state is
 881   // _thread_in_native_trans so JNI functions won't be called with
 882   // a surprising pending exception. If the thread state is going back to java,
 883   // async exception is checked in check_special_condition_for_native_trans().
 884 
 885   if (state != _thread_blocked_trans &&
 886       state != _thread_in_vm_trans &&
 887       thread->has_special_runtime_exit_condition()) {
 888     thread->handle_special_runtime_exit_condition(
 889       !thread->is_at_poll_safepoint() && (state != _thread_in_native_trans));
 890   }
 891 
 892   // cross_modify_fence is done by SafepointMechanism::block_if_requested_slow
 893   // which is the only caller here.
 894 }
 895 
 896 // ------------------------------------------------------------------------------------------------------
 897 // Exception handlers
 898 
 899 
 900 void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
 901   assert(thread->is_Java_thread(), "polling reference encountered by VM thread");
 902   assert(thread->thread_state() == _thread_in_Java, "should come from Java code");
 903   if (!ThreadLocalHandshakes) {
 904     assert(SafepointSynchronize::is_synchronizing(), "polling encountered outside safepoint synchronization");
 905   }
 906 
 907   if (log_is_enabled(Info, safepoint, stats)) {
 908     Atomic::inc(&_nof_threads_hit_polling_page);
 909   }
 910 
 911   ThreadSafepointState* state = thread->safepoint_state();
 912 
 913   state->handle_polling_page_exception();
 914 }
 915 
 916 
 917 void SafepointSynchronize::print_safepoint_timeout() {
 918   if (!timeout_error_printed) {
 919     timeout_error_printed = true;
 920     // Print out the thread info which didn't reach the safepoint for debugging
 921     // purposes (useful when there are lots of threads in the debugger).
 922     LogTarget(Warning, safepoint) lt;
 923     if (lt.is_enabled()) {
 924       ResourceMark rm;
 925       LogStream ls(lt);
 926 
 927       ls.cr();
 928       ls.print_cr("# SafepointSynchronize::begin: Timeout detected:");
 929       ls.print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint.");
 930       ls.print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:");
 931       for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur_thread = jtiwh.next(); ) {
 932         if (cur_thread->safepoint_state()->is_running()) {
 933           ls.print("# ");
 934           cur_thread->print_on(&ls);
 935           ls.cr();
 936         }
 937       }
 938       ls.print_cr("# SafepointSynchronize::begin: (End of list)");
 939     }
 940   }
 941 
 942   // To debug the long safepoint, specify both AbortVMOnSafepointTimeout &
 943   // ShowMessageBoxOnError.
 944   if (AbortVMOnSafepointTimeout) {
 945     // Send the blocking thread a signal to terminate and write an error file.
 946     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur_thread = jtiwh.next(); ) {
 947       if (cur_thread->safepoint_state()->is_running()) {
 948         if (!os::signal_thread(cur_thread, SIGILL, "blocking a safepoint")) {
 949           break; // Could not send signal. Report fatal error.
 950         }
 951         // Give cur_thread a chance to report the error and terminate the VM.
 952         os::sleep(Thread::current(), 3000, false);
 953       }
 954     }
 955     fatal("Safepoint sync time longer than " INTX_FORMAT "ms detected when executing %s.",
 956           SafepointTimeoutDelay, VMThread::vm_operation()->name());
 957   }
 958 }
 959 
 960 // -------------------------------------------------------------------------------------------------------
 961 // Implementation of ThreadSafepointState
 962 
 963 ThreadSafepointState::ThreadSafepointState(JavaThread *thread)
 964   : _at_poll_safepoint(false), _thread(thread), _safepoint_safe(false),
 965     _safepoint_id(SafepointSynchronize::InactiveSafepointCounter),
 966     _orig_thread_state(_thread_uninitialized), _next(NULL) {
 967 }
 968 
 969 void ThreadSafepointState::create(JavaThread *thread) {
 970   ThreadSafepointState *state = new ThreadSafepointState(thread);
 971   thread->set_safepoint_state(state);
 972 }
 973 
 974 void ThreadSafepointState::destroy(JavaThread *thread) {
 975   if (thread->safepoint_state()) {
 976     delete(thread->safepoint_state());
 977     thread->set_safepoint_state(NULL);
 978   }
 979 }
 980 
 981 uint64_t ThreadSafepointState::get_safepoint_id() const {
 982   return OrderAccess::load_acquire(&_safepoint_id);
 983 }
 984 
 985 void ThreadSafepointState::reset_safepoint_id() {
 986   OrderAccess::release_store(&_safepoint_id, SafepointSynchronize::InactiveSafepointCounter);
 987 }
 988 
 989 void ThreadSafepointState::set_safepoint_id(uint64_t safepoint_id) {
 990   OrderAccess::release_store(&_safepoint_id, safepoint_id);
 991 }
 992 
 993 void ThreadSafepointState::examine_state_of_thread(uint64_t safepoint_count) {
 994   assert(is_running(), "better be running or just have hit safepoint poll");
 995 
 996   JavaThreadState stable_state;
 997   if (!SafepointSynchronize::try_stable_load_state(&stable_state, _thread, safepoint_count)) {
 998     // We could not get stable state of the JavaThread.
 999     // Consider it running and just return.
1000     return;
1001   }
1002 
1003   // Save the state at the start of safepoint processing.
1004   _orig_thread_state = stable_state;
1005 
1006   // Check for a thread that is suspended. Note that thread resume tries
1007   // to grab the Threads_lock which we own here, so a thread cannot be
1008   // resumed during safepoint synchronization.
1009 
1010   // We check to see if this thread is suspended without locking to
1011   // avoid deadlocking with a third thread that is waiting for this
1012   // thread to be suspended. The third thread can notice the safepoint
1013   // that we're trying to start at the beginning of its SR_lock->wait()
1014   // call. If that happens, then the third thread will block on the
1015   // safepoint while still holding the underlying SR_lock. We won't be
1016   // able to get the SR_lock and we'll deadlock.
1017   //
1018   // We don't need to grab the SR_lock here for two reasons:
1019   // 1) The suspend flags are both volatile and are set with an
1020   //    Atomic::cmpxchg() call so we should see the suspended
1021   //    state right away.
1022   // 2) We're being called from the safepoint polling loop; if
1023   //    we don't see the suspended state on this iteration, then
1024   //    we'll come around again.
1025   //
1026   bool is_suspended = _thread->is_ext_suspended();
1027   if (is_suspended) {
1028     account_safe_thread();
1029     return;
1030   }
1031 
1032   if (safepoint_safe_with(_thread, stable_state)) {
1033     check_for_lazy_critical_native(_thread, stable_state);
1034     account_safe_thread();
1035     return;
1036   }
1037 
1038   // All other thread states will continue to run until they
1039   // transition and self-block in state _blocked
1040   // Safepoint polling in compiled code causes the Java threads to do the same.
1041   // Note: new threads may require a malloc so they must be allowed to finish
1042 
1043   assert(is_running(), "examine_state_of_thread on non-running thread");
1044   return;
1045 }
1046 
1047 void ThreadSafepointState::account_safe_thread() {
1048   SafepointSynchronize::decrement_waiting_to_block();
1049   if (_thread->in_critical()) {
1050     // Notice that this thread is in a critical section
1051     SafepointSynchronize::increment_jni_active_count();
1052   }
1053   DEBUG_ONLY(_thread->set_visited_for_critical_count(SafepointSynchronize::safepoint_counter());)
1054   assert(!_safepoint_safe, "Must be unsafe before safe");
1055   _safepoint_safe = true;
1056 }
1057 
1058 void ThreadSafepointState::restart() {
1059   assert(_safepoint_safe, "Must be safe before unsafe");
1060   _safepoint_safe = false;
1061 }
1062 
1063 void ThreadSafepointState::print_on(outputStream *st) const {
1064   const char *s = _safepoint_safe ? "_at_safepoint" : "_running";
1065 
1066   st->print_cr("Thread: " INTPTR_FORMAT
1067               "  [0x%2x] State: %s _at_poll_safepoint %d",
1068                p2i(_thread), _thread->osthread()->thread_id(), s, _at_poll_safepoint);
1069 
1070   _thread->print_thread_state_on(st);
1071 }
1072 
1073 void ThreadSafepointState::print() const { print_on(tty); }
1074 
1075 // ---------------------------------------------------------------------------------------------------------------------
1076 
1077 // Block the thread at poll or poll return for safepoint/handshake.
1078 void ThreadSafepointState::handle_polling_page_exception() {
1079 
1080   // If we're using a global poll, then the thread should not be
1081   // marked as safepoint safe yet.
1082   assert(!SafepointMechanism::uses_global_page_poll() || !_safepoint_safe,
1083          "polling page exception on thread safepoint safe");
1084 
1085   // Step 1: Find the nmethod from the return address
1086   address real_return_addr = thread()->saved_exception_pc();
1087 
1088   CodeBlob *cb = CodeCache::find_blob(real_return_addr);
1089   assert(cb != NULL && cb->is_compiled(), "return address should be in nmethod");
1090   CompiledMethod* nm = (CompiledMethod*)cb;
1091 
1092   // Find frame of caller
1093   frame stub_fr = thread()->last_frame();
1094   CodeBlob* stub_cb = stub_fr.cb();
1095   assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub");
1096   RegisterMap map(thread(), true);
1097   frame caller_fr = stub_fr.sender(&map);
1098 
1099   // Should only be poll_return or poll
1100   assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" );
1101 
1102   // This is a poll immediately before a return. The exception handling code
1103   // has already had the effect of causing the return to occur, so the execution
1104   // will continue immediately after the call. In addition, the oopmap at the
1105   // return point does not mark the return value as an oop (if it is), so
1106   // it needs a handle here to be updated.
1107   if( nm->is_at_poll_return(real_return_addr) ) {
1108     // See if return type is an oop.
1109     bool return_oop = nm->method()->is_returning_oop();
1110     Handle return_value;
1111     if (return_oop) {
1112       // The oop result has been saved on the stack together with all
1113       // the other registers. In order to preserve it over GCs we need
1114       // to keep it in a handle.
1115       oop result = caller_fr.saved_oop_result(&map);
1116       assert(oopDesc::is_oop_or_null(result), "must be oop");
1117       return_value = Handle(thread(), result);
1118       assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
1119     }
1120 
1121     // Block the thread
1122     SafepointMechanism::block_if_requested(thread());
1123 
1124     // restore oop result, if any
1125     if (return_oop) {
1126       caller_fr.set_saved_oop_result(&map, return_value());
1127     }
1128   }
1129 
1130   // This is a safepoint poll. Verify the return address and block.
1131   else {
1132     set_at_poll_safepoint(true);
1133 
1134     // verify the blob built the "return address" correctly
1135     assert(real_return_addr == caller_fr.pc(), "must match");
1136 
1137     // Block the thread
1138     SafepointMechanism::block_if_requested(thread());
1139     set_at_poll_safepoint(false);
1140 
1141     // If we have a pending async exception deoptimize the frame
1142     // as otherwise we may never deliver it.
1143     if (thread()->has_async_condition()) {
1144       ThreadInVMfromJavaNoAsyncException __tiv(thread());
1145       Deoptimization::deoptimize_frame(thread(), caller_fr.id());
1146     }
1147 
1148     // If an exception has been installed we must check for a pending deoptimization
1149     // Deoptimize frame if exception has been thrown.
1150 
1151     if (thread()->has_pending_exception() ) {
1152       RegisterMap map(thread(), true);
1153       frame caller_fr = stub_fr.sender(&map);
1154       if (caller_fr.is_deoptimized_frame()) {
1155         // The exception patch will destroy registers that are still
1156         // live and will be needed during deoptimization. Defer the
1157         // Async exception should have deferred the exception until the
1158         // next safepoint which will be detected when we get into
1159         // the interpreter so if we have an exception now things
1160         // are messed up.
1161 
1162         fatal("Exception installed and deoptimization is pending");
1163       }
1164     }
1165   }
1166 }
1167 
1168 
1169 // -------------------------------------------------------------------------------------------------------
1170 // Implementation of SafepointTracing
1171 
1172 jlong SafepointTracing::_last_safepoint_begin_time_ns = 0;
1173 jlong SafepointTracing::_last_safepoint_sync_time_ns = 0;
1174 jlong SafepointTracing::_last_safepoint_cleanup_time_ns = 0;
1175 jlong SafepointTracing::_last_safepoint_end_time_ns = 0;
1176 jlong SafepointTracing::_last_safepoint_end_time_epoch_ms = 0;
1177 jlong SafepointTracing::_last_app_time_ns = 0;
1178 int SafepointTracing::_nof_threads = 0;
1179 int SafepointTracing::_nof_running = 0;
1180 int SafepointTracing::_page_trap = 0;
1181 VM_Operation::VMOp_Type SafepointTracing::_current_type;
1182 jlong     SafepointTracing::_max_sync_time = 0;
1183 jlong     SafepointTracing::_max_vmop_time = 0;
1184 uint64_t  SafepointTracing::_op_count[VM_Operation::VMOp_Terminating] = {0};
1185 
1186 void SafepointTracing::init() {
1187   // Application start
1188   _last_safepoint_end_time_ns = os::javaTimeNanos();
1189   // amount of time since epoch
1190   _last_safepoint_end_time_epoch_ms = os::javaTimeMillis();
1191 }
1192 
1193 // Helper method to print the header.
1194 static void print_header(outputStream* st) {
1195   // The number of spaces is significant here, and should match the format
1196   // specifiers in print_statistics().
1197 
1198   st->print("VM Operation                 "
1199             "[ threads: total initial_running ]"
1200             "[ time:       sync    cleanup       vmop      total ]");
1201 
1202   st->print_cr(" page_trap_count");
1203 }
1204 
1205 // This prints a nice table.  To get the statistics to not shift due to the logging uptime
1206 // decorator, use the option as: -Xlog:safepoint+stats:[outputfile]:none
1207 void SafepointTracing::statistics_log() {
1208   LogTarget(Info, safepoint, stats) lt;
1209   assert (lt.is_enabled(), "should only be called when printing statistics is enabled");
1210   LogStream ls(lt);
1211 
1212   static int _cur_stat_index = 0;
1213 
1214   // Print header every 30 entries
1215   if ((_cur_stat_index % 30) == 0) {
1216     print_header(&ls);
1217     _cur_stat_index = 1;  // wrap
1218   } else {
1219     _cur_stat_index++;
1220   }
1221 
1222   ls.print("%-28s [       "
1223            INT32_FORMAT_W(8) "        " INT32_FORMAT_W(8) " "
1224            "]",
1225            VM_Operation::name(_current_type),
1226            _nof_threads,
1227            _nof_running);
1228   ls.print("[       "
1229            INT64_FORMAT_W(10) " " INT64_FORMAT_W(10) " "
1230            INT64_FORMAT_W(10) " " INT64_FORMAT_W(10) " ]",
1231            (int64_t)(_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns),
1232            (int64_t)(_last_safepoint_cleanup_time_ns - _last_safepoint_sync_time_ns),
1233            (int64_t)(_last_safepoint_end_time_ns - _last_safepoint_cleanup_time_ns),
1234            (int64_t)(_last_safepoint_end_time_ns - _last_safepoint_begin_time_ns));
1235 
1236   ls.print_cr(INT32_FORMAT_W(16), _page_trap);
1237 }
1238 
1239 // This method will be called when VM exits. This tries to summarize the sampling.
1240 // Current thread may already be deleted, so don't use ResourceMark.
1241 void SafepointTracing::statistics_exit_log() {
1242   if (!log_is_enabled(Info, safepoint, stats)) {
1243     return;
1244   }
1245   for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) {
1246     if (_op_count[index] != 0) {
1247       log_info(safepoint, stats)("%-28s" UINT64_FORMAT_W(10), VM_Operation::name(index),
1248                _op_count[index]);
1249     }
1250   }
1251 
1252   log_info(safepoint, stats)("VM operations coalesced during safepoint " INT64_FORMAT,
1253                               VMThread::get_coalesced_count());
1254   log_info(safepoint, stats)("Maximum sync time  " INT64_FORMAT" ns",
1255                               (int64_t)(_max_sync_time));
1256   log_info(safepoint, stats)("Maximum vm operation time (except for Exit VM operation)  "
1257                               INT64_FORMAT " ns",
1258                               (int64_t)(_max_vmop_time));
1259 }
1260 
1261 void SafepointTracing::begin(VM_Operation::VMOp_Type type) {
1262   _op_count[type]++;
1263   _current_type = type;
1264 
1265   // update the time stamp to begin recording safepoint time
1266   _last_safepoint_begin_time_ns = os::javaTimeNanos();
1267   _last_safepoint_sync_time_ns = 0;
1268   _last_safepoint_cleanup_time_ns = 0;
1269 
1270   _last_app_time_ns = _last_safepoint_begin_time_ns - _last_safepoint_end_time_ns;
1271   _last_safepoint_end_time_ns = 0;
1272 
1273   RuntimeService::record_safepoint_begin(_last_app_time_ns);
1274 }
1275 
1276 void SafepointTracing::synchronized(int nof_threads, int nof_running, int traps) {
1277   _last_safepoint_sync_time_ns = os::javaTimeNanos();
1278   _nof_threads = nof_threads;
1279   _nof_running = nof_running;
1280   _page_trap   = traps;
1281   RuntimeService::record_safepoint_synchronized(_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns);
1282 }
1283 
1284 void SafepointTracing::cleanup() {
1285   _last_safepoint_cleanup_time_ns = os::javaTimeNanos();
1286 }
1287 
1288 void SafepointTracing::end() {
1289   _last_safepoint_end_time_ns = os::javaTimeNanos();
1290   // amount of time since epoch
1291   _last_safepoint_end_time_epoch_ms = os::javaTimeMillis();
1292 
1293   if (_max_sync_time < (_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns)) {
1294     _max_sync_time = _last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns;
1295   }
1296   if (_max_vmop_time < (_last_safepoint_end_time_ns - _last_safepoint_sync_time_ns)) {
1297     _max_vmop_time = _last_safepoint_end_time_ns - _last_safepoint_sync_time_ns;
1298   }
1299   if (log_is_enabled(Info, safepoint, stats)) {
1300     statistics_log();
1301   }
1302 
1303   log_info(safepoint)(
1304      "Safepoint \"%s\", "
1305      "Time since last: " JLONG_FORMAT " ns, "
1306      "Reaching safepoint: " JLONG_FORMAT " ns, "
1307      "At safepoint: " JLONG_FORMAT " ns, "
1308      "Total: " JLONG_FORMAT " ns",
1309       VM_Operation::name(_current_type),
1310       _last_app_time_ns,
1311       _last_safepoint_cleanup_time_ns - _last_safepoint_begin_time_ns,
1312       _last_safepoint_end_time_ns     - _last_safepoint_cleanup_time_ns,
1313       _last_safepoint_end_time_ns     - _last_safepoint_begin_time_ns
1314      );
1315 
1316   RuntimeService::record_safepoint_end(_last_safepoint_end_time_ns - _last_safepoint_cleanup_time_ns);
1317 }