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