1 /*
   2  * Copyright (c) 1997, 2018, 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/interfaceSupport.inline.hpp"
  52 #include "runtime/mutexLocker.hpp"
  53 #include "runtime/orderAccess.hpp"
  54 #include "runtime/osThread.hpp"
  55 #include "runtime/safepoint.hpp"
  56 #include "runtime/safepointMechanism.inline.hpp"
  57 #include "runtime/signature.hpp"
  58 #include "runtime/stubCodeGenerator.hpp"
  59 #include "runtime/stubRoutines.hpp"
  60 #include "runtime/sweeper.hpp"
  61 #include "runtime/synchronizer.hpp"
  62 #include "runtime/thread.inline.hpp"
  63 #include "runtime/threadSMR.hpp"
  64 #include "runtime/timerTrace.hpp"
  65 #include "services/runtimeService.hpp"
  66 #include "utilities/events.hpp"
  67 #include "utilities/macros.hpp"
  68 #ifdef COMPILER1
  69 #include "c1/c1_globals.hpp"
  70 #endif
  71 
  72 template <typename E>
  73 static void set_current_safepoint_id(E* event, int adjustment = 0) {
  74   assert(event != NULL, "invariant");
  75   event->set_safepointId(SafepointSynchronize::safepoint_counter() + adjustment);
  76 }
  77 
  78 static void post_safepoint_begin_event(EventSafepointBegin* event,
  79                                        int thread_count,
  80                                        int critical_thread_count) {
  81   assert(event != NULL, "invariant");
  82   assert(event->should_commit(), "invariant");
  83   set_current_safepoint_id(event);
  84   event->set_totalThreadCount(thread_count);
  85   event->set_jniCriticalThreadCount(critical_thread_count);
  86   event->commit();
  87 }
  88 
  89 static void post_safepoint_cleanup_event(EventSafepointCleanup* event) {
  90   assert(event != NULL, "invariant");
  91   assert(event->should_commit(), "invariant");
  92   set_current_safepoint_id(event);
  93   event->commit();
  94 }
  95 
  96 static void post_safepoint_synchronize_event(EventSafepointStateSynchronization* event,
  97                                              int initial_number_of_threads,
  98                                              int threads_waiting_to_block,
  99                                              unsigned int iterations) {
 100   assert(event != NULL, "invariant");
 101   if (event->should_commit()) {
 102     // Group this event together with the ones committed after the counter is increased
 103     set_current_safepoint_id(event, 1);
 104     event->set_initialThreadCount(initial_number_of_threads);
 105     event->set_runningThreadCount(threads_waiting_to_block);
 106     event->set_iterations(iterations);
 107     event->commit();
 108   }
 109 }
 110 
 111 static void post_safepoint_wait_blocked_event(EventSafepointWaitBlocked* event,
 112                                               int initial_threads_waiting_to_block) {
 113   assert(event != NULL, "invariant");
 114   assert(event->should_commit(), "invariant");
 115   set_current_safepoint_id(event);
 116   event->set_runningThreadCount(initial_threads_waiting_to_block);
 117   event->commit();
 118 }
 119 
 120 static void post_safepoint_cleanup_task_event(EventSafepointCleanupTask* event,
 121                                               const char* name) {
 122   assert(event != NULL, "invariant");
 123   if (event->should_commit()) {
 124     set_current_safepoint_id(event);
 125     event->set_name(name);
 126     event->commit();
 127   }
 128 }
 129 
 130 static void post_safepoint_end_event(EventSafepointEnd* event) {
 131   assert(event != NULL, "invariant");
 132   if (event->should_commit()) {
 133     // Group this event together with the ones committed before the counter increased
 134     set_current_safepoint_id(event, -1);
 135     event->commit();
 136   }
 137 }
 138 
 139 // --------------------------------------------------------------------------------------------------
 140 // Implementation of Safepoint begin/end
 141 
 142 SafepointSynchronize::SynchronizeState volatile SafepointSynchronize::_state = SafepointSynchronize::_not_synchronized;
 143 volatile int  SafepointSynchronize::_waiting_to_block = 0;
 144 volatile uint64_t SafepointSynchronize::_safepoint_counter = 0;
 145 int SafepointSynchronize::_current_jni_active_count = 0;
 146 long  SafepointSynchronize::_end_of_last_safepoint = 0;
 147 int SafepointSynchronize::_defer_thr_suspend_loop_count = 4000;
 148 static const int safepoint_spin_before_yield = 2000;
 149 static volatile int PageArmed = 0 ;        // safepoint polling page is RO|RW vs PROT_NONE
 150 static volatile int TryingToBlock = 0 ;    // proximate value -- for advisory use only
 151 static bool timeout_error_printed = false;
 152 
 153 
 154 // Statistic related statics
 155 julong SafepointSynchronize::_coalesced_vmop_count = 0;
 156 static jlong _safepoint_begin_time = 0;
 157 static float _ts_of_current_safepoint = 0.0f;
 158 static volatile int _nof_threads_hit_polling_page = 0;
 159 
 160 // Roll all threads forward to a safepoint and suspend them all
 161 void SafepointSynchronize::begin() {
 162   EventSafepointBegin begin_event;
 163   Thread* myThread = Thread::current();
 164   assert(myThread->is_VM_thread(), "Only VM thread may execute a safepoint");
 165 
 166   if (log_is_enabled(Debug, safepoint, stats)) {
 167     _safepoint_begin_time = os::javaTimeNanos();
 168     _ts_of_current_safepoint = tty->time_stamp().seconds();
 169     _nof_threads_hit_polling_page = 0;
 170   }
 171 
 172   Universe::heap()->safepoint_synchronize_begin();
 173 
 174   // By getting the Threads_lock, we assure that no threads are about to start or
 175   // exit. It is released again in SafepointSynchronize::end().
 176   Threads_lock->lock();
 177 
 178   assert( _state == _not_synchronized, "trying to safepoint synchronize with wrong state");
 179 
 180   int nof_threads = Threads::number_of_threads();
 181 
 182   log_debug(safepoint)("Safepoint synchronization initiated. (%d threads)", nof_threads);
 183 
 184   RuntimeService::record_safepoint_begin();
 185 
 186   MutexLocker mu(Safepoint_lock);
 187 
 188   // Reset the count of active JNI critical threads
 189   _current_jni_active_count = 0;
 190 
 191   // Set number of threads to wait for, before we initiate the callbacks
 192   _waiting_to_block = nof_threads;
 193   TryingToBlock     = 0 ;
 194   int still_running = nof_threads;
 195 
 196   // Save the starting time, so that it can be compared to see if this has taken
 197   // too long to complete.
 198   jlong safepoint_limit_time = 0;
 199   timeout_error_printed = false;
 200 
 201   // Begin the process of bringing the system to a safepoint.
 202   // Java threads can be in several different states and are
 203   // stopped by different mechanisms:
 204   //
 205   //  1. Running interpreted
 206   //     The interpreter dispatch table is changed to force it to
 207   //     check for a safepoint condition between bytecodes.
 208   //  2. Running in native code
 209   //     When returning from the native code, a Java thread must check
 210   //     the safepoint _state to see if we must block.  If the
 211   //     VM thread sees a Java thread in native, it does
 212   //     not wait for this thread to block.  The order of the memory
 213   //     writes and reads of both the safepoint state and the Java
 214   //     threads state is critical.  In order to guarantee that the
 215   //     memory writes are serialized with respect to each other,
 216   //     the VM thread issues a memory barrier instruction.
 217   //  3. Running compiled Code
 218   //     Compiled code reads a global (Safepoint Polling) page that
 219   //     is set to fault if we are trying to get to a safepoint.
 220   //  4. Blocked
 221   //     A thread which is blocked will not be allowed to return from the
 222   //     block condition until the safepoint operation is complete.
 223   //  5. In VM or Transitioning between states
 224   //     If a Java thread is currently running in the VM or transitioning
 225   //     between states, the safepointing code will wait for the thread to
 226   //     block itself when it attempts transitions to a new state.
 227   //
 228   {
 229     EventSafepointStateSynchronization sync_event;
 230     int initial_running = 0;
 231 
 232     _state            = _synchronizing;
 233 
 234     if (SafepointMechanism::uses_thread_local_poll()) {
 235       // Arming the per thread poll while having _state != _not_synchronized means safepointing
 236       log_trace(safepoint)("Setting thread local yield flag for threads");
 237       OrderAccess::storestore(); // storestore, global state -> local state
 238       for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur = jtiwh.next(); ) {
 239         // Make sure the threads start polling, it is time to yield.
 240         SafepointMechanism::arm_local_poll(cur);
 241       }
 242     }
 243     OrderAccess::fence(); // storestore|storeload, global state -> local state
 244 
 245     if (SafepointMechanism::uses_global_page_poll()) {
 246       // Make interpreter safepoint aware
 247       Interpreter::notice_safepoints();
 248 
 249       // Make polling safepoint aware
 250       guarantee (PageArmed == 0, "invariant") ;
 251       PageArmed = 1 ;
 252       os::make_polling_page_unreadable();
 253     }
 254 
 255     // Consider using active_processor_count() ... but that call is expensive.
 256     int ncpus = os::processor_count() ;
 257     unsigned int iterations = 0;
 258 
 259     {
 260       JavaThreadIteratorWithHandle jtiwh;
 261 #ifdef ASSERT
 262       for (; JavaThread *cur = jtiwh.next(); ) {
 263         assert(cur->safepoint_state()->is_running(), "Illegal initial state");
 264         // Clear the visited flag to ensure that the critical counts are collected properly.
 265         cur->set_visited_for_critical_count(false);
 266       }
 267 #endif // ASSERT
 268 
 269       if (SafepointTimeout)
 270         safepoint_limit_time = os::javaTimeNanos() + (jlong)SafepointTimeoutDelay * MICROUNITS;
 271 
 272       // Iterate through all threads until it have been determined how to stop them all at a safepoint
 273       int steps = 0 ;
 274       while(still_running > 0) {
 275         jtiwh.rewind();
 276         for (; JavaThread *cur = jtiwh.next(); ) {
 277           assert(!cur->is_ConcurrentGC_thread(), "A concurrent GC thread is unexpectly being suspended");
 278           ThreadSafepointState *cur_state = cur->safepoint_state();
 279           if (cur_state->is_running()) {
 280             cur_state->examine_state_of_thread();
 281             if (!cur_state->is_running()) {
 282               still_running--;
 283               // consider adjusting steps downward:
 284               //   steps = 0
 285               //   steps -= NNN
 286               //   steps >>= 1
 287               //   steps = MIN(steps, 2000-100)
 288               //   if (iterations != 0) steps -= NNN
 289             }
 290             LogTarget(Trace, safepoint) lt;
 291             if (lt.is_enabled()) {
 292               ResourceMark rm;
 293               LogStream ls(lt);
 294               cur_state->print_on(&ls);
 295             }
 296           }
 297         }
 298 
 299         if (iterations == 0) {
 300           initial_running = still_running;
 301           if (log_is_enabled(Debug, safepoint, stats)) {
 302             begin_statistics(nof_threads, still_running);
 303           }
 304         }
 305 
 306         if (still_running > 0) {
 307           // Check for if it takes to long
 308           if (SafepointTimeout && safepoint_limit_time < os::javaTimeNanos()) {
 309             print_safepoint_timeout(_spinning_timeout);
 310           }
 311 
 312           // Spin to avoid context switching.
 313           // There's a tension between allowing the mutators to run (and rendezvous)
 314           // vs spinning.  As the VM thread spins, wasting cycles, it consumes CPU that
 315           // a mutator might otherwise use profitably to reach a safepoint.  Excessive
 316           // spinning by the VM thread on a saturated system can increase rendezvous latency.
 317           // Blocking or yielding incur their own penalties in the form of context switching
 318           // and the resultant loss of $ residency.
 319           //
 320           // Further complicating matters is that yield() does not work as naively expected
 321           // on many platforms -- yield() does not guarantee that any other ready threads
 322           // will run.   As such we revert to naked_short_sleep() after some number of iterations.
 323           // nakes_short_sleep() is implemented as a short unconditional sleep.
 324           // Typical operating systems round a "short" sleep period up to 10 msecs, so sleeping
 325           // can actually increase the time it takes the VM thread to detect that a system-wide
 326           // stop-the-world safepoint has been reached.  In a pathological scenario such as that
 327           // described in CR6415670 the VMthread may sleep just before the mutator(s) become safe.
 328           // In that case the mutators will be stalled waiting for the safepoint to complete and the
 329           // the VMthread will be sleeping, waiting for the mutators to rendezvous.  The VMthread
 330           // will eventually wake up and detect that all mutators are safe, at which point
 331           // we'll again make progress.
 332           //
 333           // Beware too that that the VMThread typically runs at elevated priority.
 334           // Its default priority is higher than the default mutator priority.
 335           // Obviously, this complicates spinning.
 336           //
 337           // Note too that on Windows XP SwitchThreadTo() has quite different behavior than Sleep(0).
 338           // Sleep(0) will _not yield to lower priority threads, while SwitchThreadTo() will.
 339           //
 340           // See the comments in synchronizer.cpp for additional remarks on spinning.
 341           //
 342           // In the future we might:
 343           // -- Modify the safepoint scheme to avoid potentially unbounded spinning.
 344           //    This is tricky as the path used by a thread exiting the JVM (say on
 345           //    on JNI call-out) simply stores into its state field.  The burden
 346           //    is placed on the VM thread, which must poll (spin).
 347           // -- Find something useful to do while spinning.  If the safepoint is GC-related
 348           //    we might aggressively scan the stacks of threads that are already safe.
 349           // -- YieldTo() any still-running mutators that are ready but OFFPROC.
 350           // -- Check system saturation.  If the system is not fully saturated then
 351           //    simply spin and avoid sleep/yield.
 352           // -- As still-running mutators rendezvous they could unpark the sleeping
 353           //    VMthread.  This works well for still-running mutators that become
 354           //    safe.  The VMthread must still poll for mutators that call-out.
 355           // -- Drive the policy on time-since-begin instead of iterations.
 356           // -- Consider making the spin duration a function of the # of CPUs:
 357           //    Spin = (((ncpus-1) * M) + K) + F(still_running)
 358           //    Alternately, instead of counting iterations of the outer loop
 359           //    we could count the # of threads visited in the inner loop, above.
 360           // -- On windows consider using the return value from SwitchThreadTo()
 361           //    to drive subsequent spin/SwitchThreadTo()/Sleep(N) decisions.
 362 
 363           if (int(iterations) == -1) { // overflow - something is wrong.
 364             // We can only overflow here when we are using global
 365             // polling pages. We keep this guarantee in its original
 366             // form so that searches of the bug database for this
 367             // failure mode find the right bugs.
 368             guarantee (PageArmed == 0, "invariant");
 369           }
 370 
 371           // Instead of (ncpus > 1) consider either (still_running < (ncpus + EPSILON)) or
 372           // ((still_running + _waiting_to_block - TryingToBlock)) < ncpus)
 373           ++steps ;
 374           if (ncpus > 1 && steps < safepoint_spin_before_yield) {
 375             SpinPause() ;     // MP-Polite spin
 376           } else
 377             if (steps < _defer_thr_suspend_loop_count) {
 378               os::naked_yield() ;
 379             } else {
 380               os::naked_short_sleep(1);
 381             }
 382 
 383           iterations ++ ;
 384         }
 385         assert(iterations < (uint)max_jint, "We have been iterating in the safepoint loop too long");
 386       }
 387     } // ThreadsListHandle destroyed here.
 388     assert(still_running == 0, "sanity check");
 389 
 390     if (log_is_enabled(Debug, safepoint, stats)) {
 391       update_statistics_on_spin_end();
 392     }
 393     if (sync_event.should_commit()) {
 394       post_safepoint_synchronize_event(&sync_event, initial_running, _waiting_to_block, iterations);
 395     }
 396   }
 397 
 398   // wait until all threads are stopped
 399   {
 400     EventSafepointWaitBlocked wait_blocked_event;
 401     int initial_waiting_to_block = _waiting_to_block;
 402 
 403     while (_waiting_to_block > 0) {
 404       log_debug(safepoint)("Waiting for %d thread(s) to block", _waiting_to_block);
 405       if (!SafepointTimeout || timeout_error_printed) {
 406         Safepoint_lock->wait(true);  // true, means with no safepoint checks
 407       } else {
 408         // Compute remaining time
 409         jlong remaining_time = safepoint_limit_time - os::javaTimeNanos();
 410 
 411         // If there is no remaining time, then there is an error
 412         if (remaining_time < 0 || Safepoint_lock->wait(true, remaining_time / MICROUNITS)) {
 413           print_safepoint_timeout(_blocking_timeout);
 414         }
 415       }
 416     }
 417     assert(_waiting_to_block == 0, "sanity check");
 418 
 419 #ifndef PRODUCT
 420     if (SafepointTimeout) {
 421       jlong current_time = os::javaTimeNanos();
 422       if (safepoint_limit_time < current_time) {
 423         log_warning(safepoint)("# SafepointSynchronize: Finished after "
 424                       INT64_FORMAT_W(6) " ms",
 425                       (int64_t)((current_time - safepoint_limit_time) / MICROUNITS +
 426                                 (jlong)SafepointTimeoutDelay));
 427       }
 428     }
 429 #endif
 430 
 431     assert((_safepoint_counter & 0x1) == 0, "must be even");
 432     assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
 433     _safepoint_counter ++;
 434 
 435     // Record state
 436     _state = _synchronized;
 437 
 438     OrderAccess::fence();
 439     if (wait_blocked_event.should_commit()) {
 440       post_safepoint_wait_blocked_event(&wait_blocked_event, initial_waiting_to_block);
 441     }
 442   }
 443 
 444 #ifdef ASSERT
 445   // Make sure all the threads were visited.
 446   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur = jtiwh.next(); ) {
 447     assert(cur->was_visited_for_critical_count(), "missed a thread");
 448   }
 449 #endif // ASSERT
 450 
 451   // Update the count of active JNI critical regions
 452   GCLocker::set_jni_lock_count(_current_jni_active_count);
 453 
 454   log_info(safepoint)("Entering safepoint region: %s", VMThread::vm_safepoint_description());
 455 
 456   RuntimeService::record_safepoint_synchronized();
 457   if (log_is_enabled(Debug, safepoint, stats)) {
 458     update_statistics_on_sync_end(os::javaTimeNanos());
 459   }
 460 
 461   // Call stuff that needs to be run when a safepoint is just about to be completed
 462   {
 463     EventSafepointCleanup cleanup_event;
 464     do_cleanup_tasks();
 465     if (cleanup_event.should_commit()) {
 466       post_safepoint_cleanup_event(&cleanup_event);
 467     }
 468   }
 469 
 470   if (log_is_enabled(Debug, safepoint, stats)) {
 471     // Record how much time spend on the above cleanup tasks
 472     update_statistics_on_cleanup_end(os::javaTimeNanos());
 473   }
 474 
 475   if (begin_event.should_commit()) {
 476     post_safepoint_begin_event(&begin_event, nof_threads, _current_jni_active_count);
 477   }
 478 }
 479 
 480 // Wake up all threads, so they are ready to resume execution after the safepoint
 481 // operation has been carried out
 482 void SafepointSynchronize::end() {
 483   assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
 484   assert((_safepoint_counter & 0x1) == 1, "must be odd");
 485   EventSafepointEnd event;
 486   _safepoint_counter ++;
 487   // memory fence isn't required here since an odd _safepoint_counter
 488   // value can do no harm and a fence is issued below anyway.
 489 
 490   DEBUG_ONLY(Thread* myThread = Thread::current();)
 491   assert(myThread->is_VM_thread(), "Only VM thread can execute a safepoint");
 492 
 493   if (log_is_enabled(Debug, safepoint, stats)) {
 494     end_statistics(os::javaTimeNanos());
 495   }
 496 
 497   {
 498     JavaThreadIteratorWithHandle jtiwh;
 499 #ifdef ASSERT
 500     // A pending_exception cannot be installed during a safepoint.  The threads
 501     // may install an async exception after they come back from a safepoint into
 502     // pending_exception after they unblock.  But that should happen later.
 503     for (; JavaThread *cur = jtiwh.next(); ) {
 504       assert (!(cur->has_pending_exception() &&
 505                 cur->safepoint_state()->is_at_poll_safepoint()),
 506               "safepoint installed a pending exception");
 507     }
 508 #endif // ASSERT
 509 
 510     if (PageArmed) {
 511       assert(SafepointMechanism::uses_global_page_poll(), "sanity");
 512       // Make polling safepoint aware
 513       os::make_polling_page_readable();
 514       PageArmed = 0 ;
 515     }
 516 
 517     if (SafepointMechanism::uses_global_page_poll()) {
 518       // Remove safepoint check from interpreter
 519       Interpreter::ignore_safepoints();
 520     }
 521 
 522     {
 523       MutexLocker mu(Safepoint_lock);
 524 
 525       assert(_state == _synchronized, "must be synchronized before ending safepoint synchronization");
 526 
 527       if (SafepointMechanism::uses_thread_local_poll()) {
 528         _state = _not_synchronized;
 529         OrderAccess::storestore(); // global state -> local state
 530         jtiwh.rewind();
 531         for (; JavaThread *current = jtiwh.next(); ) {
 532           ThreadSafepointState* cur_state = current->safepoint_state();
 533           cur_state->restart(); // TSS _running
 534           SafepointMechanism::disarm_local_poll(current);
 535         }
 536         log_info(safepoint)("Leaving safepoint region");
 537       } else {
 538         // Set to not synchronized, so the threads will not go into the signal_thread_blocked method
 539         // when they get restarted.
 540         _state = _not_synchronized;
 541         OrderAccess::fence();
 542 
 543         log_info(safepoint)("Leaving safepoint region");
 544 
 545         // Start suspended threads
 546         jtiwh.rewind();
 547         for (; JavaThread *current = jtiwh.next(); ) {
 548           ThreadSafepointState* cur_state = current->safepoint_state();
 549           assert(cur_state->type() != ThreadSafepointState::_running, "Thread not suspended at safepoint");
 550           cur_state->restart();
 551           assert(cur_state->is_running(), "safepoint state has not been reset");
 552         }
 553       }
 554 
 555       RuntimeService::record_safepoint_end();
 556 
 557       // Release threads lock, so threads can be created/destroyed again.
 558       // It will also release all threads blocked in signal_thread_blocked.
 559       Threads_lock->unlock();
 560     }
 561   } // ThreadsListHandle destroyed here.
 562 
 563   Universe::heap()->safepoint_synchronize_end();
 564   // record this time so VMThread can keep track how much time has elapsed
 565   // since last safepoint.
 566   _end_of_last_safepoint = os::javaTimeMillis();
 567   if (event.should_commit()) {
 568     post_safepoint_end_event(&event);
 569   }
 570 }
 571 
 572 bool SafepointSynchronize::is_cleanup_needed() {
 573   // Need a safepoint if there are many monitors to deflate.
 574   if (ObjectSynchronizer::is_cleanup_needed()) return true;
 575   // Need a safepoint if some inline cache buffers is non-empty
 576   if (!InlineCacheBuffer::is_empty()) return true;
 577   return false;
 578 }
 579 
 580 class ParallelSPCleanupThreadClosure : public ThreadClosure {
 581 private:
 582   CodeBlobClosure* _nmethod_cl;
 583   DeflateMonitorCounters* _counters;
 584 
 585 public:
 586   ParallelSPCleanupThreadClosure(DeflateMonitorCounters* counters) :
 587     _nmethod_cl(UseCodeAging ? NMethodSweeper::prepare_reset_hotness_counters() : NULL),
 588     _counters(counters) {}
 589 
 590   void do_thread(Thread* thread) {
 591     ObjectSynchronizer::deflate_thread_local_monitors(thread, _counters);
 592     if (_nmethod_cl != NULL && thread->is_Java_thread() &&
 593         ! thread->is_Code_cache_sweeper_thread()) {
 594       JavaThread* jt = (JavaThread*) thread;
 595       jt->nmethods_do(_nmethod_cl);
 596     }
 597   }
 598 };
 599 
 600 class ParallelSPCleanupTask : public AbstractGangTask {
 601 private:
 602   SubTasksDone _subtasks;
 603   ParallelSPCleanupThreadClosure _cleanup_threads_cl;
 604   uint _num_workers;
 605   DeflateMonitorCounters* _counters;
 606 public:
 607   ParallelSPCleanupTask(uint num_workers, DeflateMonitorCounters* counters) :
 608     AbstractGangTask("Parallel Safepoint Cleanup"),
 609     _subtasks(SubTasksDone(SafepointSynchronize::SAFEPOINT_CLEANUP_NUM_TASKS)),
 610     _cleanup_threads_cl(ParallelSPCleanupThreadClosure(counters)),
 611     _num_workers(num_workers),
 612     _counters(counters) {}
 613 
 614   void work(uint worker_id) {
 615     // All threads deflate monitors and mark nmethods (if necessary).
 616     Threads::possibly_parallel_threads_do(true, &_cleanup_threads_cl);
 617 
 618     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_DEFLATE_MONITORS)) {
 619       const char* name = "deflating idle monitors";
 620       EventSafepointCleanupTask event;
 621       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 622       ObjectSynchronizer::deflate_idle_monitors(_counters);
 623       if (event.should_commit()) {
 624         post_safepoint_cleanup_task_event(&event, name);
 625       }
 626     }
 627 
 628     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_UPDATE_INLINE_CACHES)) {
 629       const char* name = "updating inline caches";
 630       EventSafepointCleanupTask event;
 631       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 632       InlineCacheBuffer::update_inline_caches();
 633       if (event.should_commit()) {
 634         post_safepoint_cleanup_task_event(&event, name);
 635       }
 636     }
 637 
 638     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_COMPILATION_POLICY)) {
 639       const char* name = "compilation policy safepoint handler";
 640       EventSafepointCleanupTask event;
 641       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 642       CompilationPolicy::policy()->do_safepoint_work();
 643       if (event.should_commit()) {
 644         post_safepoint_cleanup_task_event(&event, name);
 645       }
 646     }
 647 
 648     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_SYMBOL_TABLE_REHASH)) {
 649       if (SymbolTable::needs_rehashing()) {
 650         const char* name = "rehashing symbol table";
 651         EventSafepointCleanupTask event;
 652         TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 653         SymbolTable::rehash_table();
 654         if (event.should_commit()) {
 655           post_safepoint_cleanup_task_event(&event, name);
 656         }
 657       }
 658     }
 659 
 660     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_STRING_TABLE_REHASH)) {
 661       if (StringTable::needs_rehashing()) {
 662         const char* name = "rehashing string table";
 663         EventSafepointCleanupTask event;
 664         TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 665         StringTable::rehash_table();
 666         if (event.should_commit()) {
 667           post_safepoint_cleanup_task_event(&event, name);
 668         }
 669       }
 670     }
 671 
 672     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_CLD_PURGE)) {
 673       // CMS delays purging the CLDG until the beginning of the next safepoint and to
 674       // make sure concurrent sweep is done
 675       const char* name = "purging class loader data graph";
 676       EventSafepointCleanupTask event;
 677       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 678       ClassLoaderDataGraph::purge_if_needed();
 679       if (event.should_commit()) {
 680         post_safepoint_cleanup_task_event(&event, name);
 681       }
 682     }
 683 
 684     if (_subtasks.try_claim_task(SafepointSynchronize::SAFEPOINT_CLEANUP_SYSTEM_DICTIONARY_RESIZE)) {
 685       const char* name = "resizing system dictionaries";
 686       EventSafepointCleanupTask event;
 687       TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 688       ClassLoaderDataGraph::resize_if_needed();
 689       if (event.should_commit()) {
 690         post_safepoint_cleanup_task_event(&event, name);
 691       }
 692     }
 693 
 694     _subtasks.all_tasks_completed(_num_workers);
 695   }
 696 };
 697 
 698 // Various cleaning tasks that should be done periodically at safepoints.
 699 void SafepointSynchronize::do_cleanup_tasks() {
 700 
 701   TraceTime timer("safepoint cleanup tasks", TRACETIME_LOG(Info, safepoint, cleanup));
 702 
 703   // Prepare for monitor deflation.
 704   DeflateMonitorCounters deflate_counters;
 705   ObjectSynchronizer::prepare_deflate_idle_monitors(&deflate_counters);
 706 
 707   CollectedHeap* heap = Universe::heap();
 708   assert(heap != NULL, "heap not initialized yet?");
 709   WorkGang* cleanup_workers = heap->get_safepoint_workers();
 710   if (cleanup_workers != NULL) {
 711     // Parallel cleanup using GC provided thread pool.
 712     uint num_cleanup_workers = cleanup_workers->active_workers();
 713     ParallelSPCleanupTask cleanup(num_cleanup_workers, &deflate_counters);
 714     StrongRootsScope srs(num_cleanup_workers);
 715     cleanup_workers->run_task(&cleanup);
 716   } else {
 717     // Serial cleanup using VMThread.
 718     ParallelSPCleanupTask cleanup(1, &deflate_counters);
 719     StrongRootsScope srs(1);
 720     cleanup.work(0);
 721   }
 722 
 723   // Needs to be done single threaded by the VMThread.  This walks
 724   // the thread stacks looking for references to metadata before
 725   // deciding to remove it from the metaspaces.
 726   if (ClassLoaderDataGraph::should_clean_metaspaces_and_reset()) {
 727     const char* name = "cleanup live ClassLoaderData metaspaces";
 728     TraceTime timer(name, TRACETIME_LOG(Info, safepoint, cleanup));
 729     ClassLoaderDataGraph::walk_metadata_and_clean_metaspaces();
 730   }
 731 
 732   // Finish monitor deflation.
 733   ObjectSynchronizer::finish_deflate_idle_monitors(&deflate_counters);
 734 
 735   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
 736 }
 737 
 738 
 739 bool SafepointSynchronize::safepoint_safe(JavaThread *thread, JavaThreadState state) {
 740   switch(state) {
 741   case _thread_in_native:
 742     // native threads are safe if they have no java stack or have walkable stack
 743     return !thread->has_last_Java_frame() || thread->frame_anchor()->walkable();
 744 
 745    // blocked threads should have already have walkable stack
 746   case _thread_blocked:
 747     assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "blocked and not walkable");
 748     return true;
 749 
 750   default:
 751     return false;
 752   }
 753 }
 754 
 755 
 756 // See if the thread is running inside a lazy critical native and
 757 // update the thread critical count if so.  Also set a suspend flag to
 758 // cause the native wrapper to return into the JVM to do the unlock
 759 // once the native finishes.
 760 void SafepointSynchronize::check_for_lazy_critical_native(JavaThread *thread, JavaThreadState state) {
 761   if (state == _thread_in_native &&
 762       thread->has_last_Java_frame() &&
 763       thread->frame_anchor()->walkable()) {
 764     // This thread might be in a critical native nmethod so look at
 765     // the top of the stack and increment the critical count if it
 766     // is.
 767     frame wrapper_frame = thread->last_frame();
 768     CodeBlob* stub_cb = wrapper_frame.cb();
 769     if (stub_cb != NULL &&
 770         stub_cb->is_nmethod() &&
 771         stub_cb->as_nmethod_or_null()->is_lazy_critical_native()) {
 772       // A thread could potentially be in a critical native across
 773       // more than one safepoint, so only update the critical state on
 774       // the first one.  When it returns it will perform the unlock.
 775       if (!thread->do_critical_native_unlock()) {
 776 #ifdef ASSERT
 777         if (!thread->in_critical()) {
 778           GCLocker::increment_debug_jni_lock_count();
 779         }
 780 #endif
 781         thread->enter_critical();
 782         // Make sure the native wrapper calls back on return to
 783         // perform the needed critical unlock.
 784         thread->set_critical_native_unlock();
 785       }
 786     }
 787   }
 788 }
 789 
 790 
 791 
 792 // -------------------------------------------------------------------------------------------------------
 793 // Implementation of Safepoint callback point
 794 
 795 void SafepointSynchronize::block(JavaThread *thread) {
 796   assert(thread != NULL, "thread must be set");
 797   assert(thread->is_Java_thread(), "not a Java thread");
 798 
 799   // Threads shouldn't block if they are in the middle of printing, but...
 800   ttyLocker::break_tty_lock_for_safepoint(os::current_thread_id());
 801 
 802   // Only bail from the block() call if the thread is gone from the
 803   // thread list; starting to exit should still block.
 804   if (thread->is_terminated()) {
 805      // block current thread if we come here from native code when VM is gone
 806      thread->block_if_vm_exited();
 807 
 808      // otherwise do nothing
 809      return;
 810   }
 811 
 812   JavaThreadState state = thread->thread_state();
 813   thread->frame_anchor()->make_walkable(thread);
 814 
 815   // Check that we have a valid thread_state at this point
 816   switch(state) {
 817     case _thread_in_vm_trans:
 818     case _thread_in_Java:        // From compiled code
 819 
 820       // We are highly likely to block on the Safepoint_lock. In order to avoid blocking in this case,
 821       // we pretend we are still in the VM.
 822       thread->set_thread_state(_thread_in_vm);
 823 
 824       if (is_synchronizing()) {
 825          Atomic::inc (&TryingToBlock) ;
 826       }
 827 
 828       // We will always be holding the Safepoint_lock when we are examine the state
 829       // of a thread. Hence, the instructions between the Safepoint_lock->lock() and
 830       // Safepoint_lock->unlock() are happening atomic with regards to the safepoint code
 831       Safepoint_lock->lock_without_safepoint_check();
 832       if (is_synchronizing()) {
 833         // Decrement the number of threads to wait for and signal vm thread
 834         assert(_waiting_to_block > 0, "sanity check");
 835         _waiting_to_block--;
 836         thread->safepoint_state()->set_has_called_back(true);
 837 
 838         DEBUG_ONLY(thread->set_visited_for_critical_count(true));
 839         if (thread->in_critical()) {
 840           // Notice that this thread is in a critical section
 841           increment_jni_active_count();
 842         }
 843 
 844         // Consider (_waiting_to_block < 2) to pipeline the wakeup of the VM thread
 845         if (_waiting_to_block == 0) {
 846           Safepoint_lock->notify_all();
 847         }
 848       }
 849 
 850       // We transition the thread to state _thread_blocked here, but
 851       // we can't do our usual check for external suspension and then
 852       // self-suspend after the lock_without_safepoint_check() call
 853       // below because we are often called during transitions while
 854       // we hold different locks. That would leave us suspended while
 855       // holding a resource which results in deadlocks.
 856       thread->set_thread_state(_thread_blocked);
 857       Safepoint_lock->unlock();
 858 
 859       // We now try to acquire the threads lock. Since this lock is hold by the VM thread during
 860       // the entire safepoint, the threads will all line up here during the safepoint.
 861       Threads_lock->lock_without_safepoint_check();
 862       // restore original state. This is important if the thread comes from compiled code, so it
 863       // will continue to execute with the _thread_in_Java state.
 864       thread->set_thread_state(state);
 865       Threads_lock->unlock();
 866       break;
 867 
 868     case _thread_in_native_trans:
 869     case _thread_blocked_trans:
 870     case _thread_new_trans:
 871       if (thread->safepoint_state()->type() == ThreadSafepointState::_call_back) {
 872         thread->print_thread_state();
 873         fatal("Deadlock in safepoint code.  "
 874               "Should have called back to the VM before blocking.");
 875       }
 876 
 877       // We transition the thread to state _thread_blocked here, but
 878       // we can't do our usual check for external suspension and then
 879       // self-suspend after the lock_without_safepoint_check() call
 880       // below because we are often called during transitions while
 881       // we hold different locks. That would leave us suspended while
 882       // holding a resource which results in deadlocks.
 883       thread->set_thread_state(_thread_blocked);
 884 
 885       // It is not safe to suspend a thread if we discover it is in _thread_in_native_trans. Hence,
 886       // the safepoint code might still be waiting for it to block. We need to change the state here,
 887       // so it can see that it is at a safepoint.
 888 
 889       // Block until the safepoint operation is completed.
 890       Threads_lock->lock_without_safepoint_check();
 891 
 892       // Restore state
 893       thread->set_thread_state(state);
 894 
 895       Threads_lock->unlock();
 896       break;
 897 
 898     default:
 899      fatal("Illegal threadstate encountered: %d", state);
 900   }
 901 
 902   // Check for pending. async. exceptions or suspends - except if the
 903   // thread was blocked inside the VM. has_special_runtime_exit_condition()
 904   // is called last since it grabs a lock and we only want to do that when
 905   // we must.
 906   //
 907   // Note: we never deliver an async exception at a polling point as the
 908   // compiler may not have an exception handler for it. The polling
 909   // code will notice the async and deoptimize and the exception will
 910   // be delivered. (Polling at a return point is ok though). Sure is
 911   // a lot of bother for a deprecated feature...
 912   //
 913   // We don't deliver an async exception if the thread state is
 914   // _thread_in_native_trans so JNI functions won't be called with
 915   // a surprising pending exception. If the thread state is going back to java,
 916   // async exception is checked in check_special_condition_for_native_trans().
 917 
 918   if (state != _thread_blocked_trans &&
 919       state != _thread_in_vm_trans &&
 920       thread->has_special_runtime_exit_condition()) {
 921     thread->handle_special_runtime_exit_condition(
 922       !thread->is_at_poll_safepoint() && (state != _thread_in_native_trans));
 923   }
 924 }
 925 
 926 // ------------------------------------------------------------------------------------------------------
 927 // Exception handlers
 928 
 929 
 930 void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
 931   assert(thread->is_Java_thread(), "polling reference encountered by VM thread");
 932   assert(thread->thread_state() == _thread_in_Java, "should come from Java code");
 933   if (!ThreadLocalHandshakes) {
 934     assert(SafepointSynchronize::is_synchronizing(), "polling encountered outside safepoint synchronization");
 935   }
 936 
 937   if (log_is_enabled(Debug, safepoint, stats)) {
 938     Atomic::inc(&_nof_threads_hit_polling_page);
 939   }
 940 
 941   ThreadSafepointState* state = thread->safepoint_state();
 942 
 943   state->handle_polling_page_exception();
 944 }
 945 
 946 
 947 void SafepointSynchronize::print_safepoint_timeout(SafepointTimeoutReason reason) {
 948   if (!timeout_error_printed) {
 949     timeout_error_printed = true;
 950     // Print out the thread info which didn't reach the safepoint for debugging
 951     // purposes (useful when there are lots of threads in the debugger).
 952     LogTarget(Warning, safepoint) lt;
 953     if (lt.is_enabled()) {
 954       ResourceMark rm;
 955       LogStream ls(lt);
 956 
 957       ls.cr();
 958       ls.print_cr("# SafepointSynchronize::begin: Timeout detected:");
 959       if (reason ==  _spinning_timeout) {
 960         ls.print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint.");
 961       } else if (reason == _blocking_timeout) {
 962         ls.print_cr("# SafepointSynchronize::begin: Timed out while waiting for threads to stop.");
 963       }
 964 
 965       ls.print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:");
 966       ThreadSafepointState *cur_state;
 967       for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur_thread = jtiwh.next(); ) {
 968         cur_state = cur_thread->safepoint_state();
 969 
 970         if (cur_thread->thread_state() != _thread_blocked &&
 971           ((reason == _spinning_timeout && cur_state->is_running()) ||
 972              (reason == _blocking_timeout && !cur_state->has_called_back()))) {
 973           ls.print("# ");
 974           cur_thread->print_on(&ls);
 975           ls.cr();
 976         }
 977       }
 978       ls.print_cr("# SafepointSynchronize::begin: (End of list)");
 979     }
 980   }
 981 
 982   // To debug the long safepoint, specify both AbortVMOnSafepointTimeout &
 983   // ShowMessageBoxOnError.
 984   if (AbortVMOnSafepointTimeout) {
 985     fatal("Safepoint sync time longer than " INTX_FORMAT "ms detected when executing %s.",
 986           SafepointTimeoutDelay, VMThread::vm_safepoint_description());
 987   }
 988 }
 989 
 990 
 991 // -------------------------------------------------------------------------------------------------------
 992 // Implementation of ThreadSafepointState
 993 
 994 ThreadSafepointState::ThreadSafepointState(JavaThread *thread) {
 995   _thread = thread;
 996   _type   = _running;
 997   _has_called_back = false;
 998   _at_poll_safepoint = false;
 999 }
1000 
1001 void ThreadSafepointState::create(JavaThread *thread) {
1002   ThreadSafepointState *state = new ThreadSafepointState(thread);
1003   thread->set_safepoint_state(state);
1004 }
1005 
1006 void ThreadSafepointState::destroy(JavaThread *thread) {
1007   if (thread->safepoint_state()) {
1008     delete(thread->safepoint_state());
1009     thread->set_safepoint_state(NULL);
1010   }
1011 }
1012 
1013 void ThreadSafepointState::examine_state_of_thread() {
1014   assert(is_running(), "better be running or just have hit safepoint poll");
1015 
1016   JavaThreadState state = _thread->thread_state();
1017 
1018   // Save the state at the start of safepoint processing.
1019   _orig_thread_state = state;
1020 
1021   // Check for a thread that is suspended. Note that thread resume tries
1022   // to grab the Threads_lock which we own here, so a thread cannot be
1023   // resumed during safepoint synchronization.
1024 
1025   // We check to see if this thread is suspended without locking to
1026   // avoid deadlocking with a third thread that is waiting for this
1027   // thread to be suspended. The third thread can notice the safepoint
1028   // that we're trying to start at the beginning of its SR_lock->wait()
1029   // call. If that happens, then the third thread will block on the
1030   // safepoint while still holding the underlying SR_lock. We won't be
1031   // able to get the SR_lock and we'll deadlock.
1032   //
1033   // We don't need to grab the SR_lock here for two reasons:
1034   // 1) The suspend flags are both volatile and are set with an
1035   //    Atomic::cmpxchg() call so we should see the suspended
1036   //    state right away.
1037   // 2) We're being called from the safepoint polling loop; if
1038   //    we don't see the suspended state on this iteration, then
1039   //    we'll come around again.
1040   //
1041   bool is_suspended = _thread->is_ext_suspended();
1042   if (is_suspended) {
1043     roll_forward(_at_safepoint);
1044     return;
1045   }
1046 
1047   // Some JavaThread states have an initial safepoint state of
1048   // running, but are actually at a safepoint. We will happily
1049   // agree and update the safepoint state here.
1050   if (SafepointSynchronize::safepoint_safe(_thread, state)) {
1051     SafepointSynchronize::check_for_lazy_critical_native(_thread, state);
1052     roll_forward(_at_safepoint);
1053     return;
1054   }
1055 
1056   if (state == _thread_in_vm) {
1057     roll_forward(_call_back);
1058     return;
1059   }
1060 
1061   // All other thread states will continue to run until they
1062   // transition and self-block in state _blocked
1063   // Safepoint polling in compiled code causes the Java threads to do the same.
1064   // Note: new threads may require a malloc so they must be allowed to finish
1065 
1066   assert(is_running(), "examine_state_of_thread on non-running thread");
1067   return;
1068 }
1069 
1070 // Returns true is thread could not be rolled forward at present position.
1071 void ThreadSafepointState::roll_forward(suspend_type type) {
1072   _type = type;
1073 
1074   switch(_type) {
1075     case _at_safepoint:
1076       SafepointSynchronize::signal_thread_at_safepoint();
1077       DEBUG_ONLY(_thread->set_visited_for_critical_count(true));
1078       if (_thread->in_critical()) {
1079         // Notice that this thread is in a critical section
1080         SafepointSynchronize::increment_jni_active_count();
1081       }
1082       break;
1083 
1084     case _call_back:
1085       set_has_called_back(false);
1086       break;
1087 
1088     case _running:
1089     default:
1090       ShouldNotReachHere();
1091   }
1092 }
1093 
1094 void ThreadSafepointState::restart() {
1095   switch(type()) {
1096     case _at_safepoint:
1097     case _call_back:
1098       break;
1099 
1100     case _running:
1101     default:
1102        tty->print_cr("restart thread " INTPTR_FORMAT " with state %d",
1103                      p2i(_thread), _type);
1104        _thread->print();
1105       ShouldNotReachHere();
1106   }
1107   _type = _running;
1108   set_has_called_back(false);
1109 }
1110 
1111 
1112 void ThreadSafepointState::print_on(outputStream *st) const {
1113   const char *s = NULL;
1114 
1115   switch(_type) {
1116     case _running                : s = "_running";              break;
1117     case _at_safepoint           : s = "_at_safepoint";         break;
1118     case _call_back              : s = "_call_back";            break;
1119     default:
1120       ShouldNotReachHere();
1121   }
1122 
1123   st->print_cr("Thread: " INTPTR_FORMAT
1124               "  [0x%2x] State: %s _has_called_back %d _at_poll_safepoint %d",
1125                p2i(_thread), _thread->osthread()->thread_id(), s, _has_called_back,
1126                _at_poll_safepoint);
1127 
1128   _thread->print_thread_state_on(st);
1129 }
1130 
1131 // ---------------------------------------------------------------------------------------------------------------------
1132 
1133 // Block the thread at poll or poll return for safepoint/handshake.
1134 void ThreadSafepointState::handle_polling_page_exception() {
1135 
1136   // Check state.  block() will set thread state to thread_in_vm which will
1137   // cause the safepoint state _type to become _call_back.
1138   suspend_type t = type();
1139   assert(!SafepointMechanism::uses_global_page_poll() || t == ThreadSafepointState::_running,
1140          "polling page exception on thread not running state: %u", uint(t));
1141 
1142   // Step 1: Find the nmethod from the return address
1143   address real_return_addr = thread()->saved_exception_pc();
1144 
1145   CodeBlob *cb = CodeCache::find_blob(real_return_addr);
1146   assert(cb != NULL && cb->is_compiled(), "return address should be in nmethod");
1147   CompiledMethod* nm = (CompiledMethod*)cb;
1148 
1149   // Find frame of caller
1150   frame stub_fr = thread()->last_frame();
1151   CodeBlob* stub_cb = stub_fr.cb();
1152   assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub");
1153   RegisterMap map(thread(), true);
1154   frame caller_fr = stub_fr.sender(&map);
1155 
1156   // Should only be poll_return or poll
1157   assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" );
1158 
1159   // This is a poll immediately before a return. The exception handling code
1160   // has already had the effect of causing the return to occur, so the execution
1161   // will continue immediately after the call. In addition, the oopmap at the
1162   // return point does not mark the return value as an oop (if it is), so
1163   // it needs a handle here to be updated.
1164   if( nm->is_at_poll_return(real_return_addr) ) {
1165     // See if return type is an oop.
1166     bool return_oop = nm->method()->is_returning_oop();
1167     Handle return_value;
1168     if (return_oop) {
1169       // The oop result has been saved on the stack together with all
1170       // the other registers. In order to preserve it over GCs we need
1171       // to keep it in a handle.
1172       oop result = caller_fr.saved_oop_result(&map);
1173       assert(oopDesc::is_oop_or_null(result), "must be oop");
1174       return_value = Handle(thread(), result);
1175       assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
1176     }
1177 
1178     // Block the thread
1179     SafepointMechanism::block_if_requested(thread());
1180 
1181     // restore oop result, if any
1182     if (return_oop) {
1183       caller_fr.set_saved_oop_result(&map, return_value());
1184     }
1185   }
1186 
1187   // This is a safepoint poll. Verify the return address and block.
1188   else {
1189     set_at_poll_safepoint(true);
1190 
1191     // verify the blob built the "return address" correctly
1192     assert(real_return_addr == caller_fr.pc(), "must match");
1193 
1194     // Block the thread
1195     SafepointMechanism::block_if_requested(thread());
1196     set_at_poll_safepoint(false);
1197 
1198     // If we have a pending async exception deoptimize the frame
1199     // as otherwise we may never deliver it.
1200     if (thread()->has_async_condition()) {
1201       ThreadInVMfromJavaNoAsyncException __tiv(thread());
1202       Deoptimization::deoptimize_frame(thread(), caller_fr.id());
1203     }
1204 
1205     // If an exception has been installed we must check for a pending deoptimization
1206     // Deoptimize frame if exception has been thrown.
1207 
1208     if (thread()->has_pending_exception() ) {
1209       RegisterMap map(thread(), true);
1210       frame caller_fr = stub_fr.sender(&map);
1211       if (caller_fr.is_deoptimized_frame()) {
1212         // The exception patch will destroy registers that are still
1213         // live and will be needed during deoptimization. Defer the
1214         // Async exception should have deferred the exception until the
1215         // next safepoint which will be detected when we get into
1216         // the interpreter so if we have an exception now things
1217         // are messed up.
1218 
1219         fatal("Exception installed and deoptimization is pending");
1220       }
1221     }
1222   }
1223 }
1224 
1225 
1226 //
1227 //                     Statistics & Instrumentations
1228 //
1229 struct SafepointStats {
1230     float  _time_stamp;                        // record when the current safepoint occurs in seconds
1231     int    _vmop_type;                         // tyep of VM operation triggers the safepoint
1232     int    _nof_total_threads;                 // total number of Java threads
1233     int    _nof_initial_running_threads;       // total number of initially seen running threads
1234     int    _nof_threads_wait_to_block;         // total number of threads waiting for to block
1235     bool   _page_armed;                        // true if polling page is armed, false otherwise
1236     int _nof_threads_hit_page_trap;            // total number of threads hitting the page trap
1237     jlong  _time_to_spin;                      // total time in millis spent in spinning
1238     jlong  _time_to_wait_to_block;             // total time in millis spent in waiting for to block
1239     jlong  _time_to_do_cleanups;               // total time in millis spent in performing cleanups
1240     jlong  _time_to_sync;                      // total time in millis spent in getting to _synchronized
1241     jlong  _time_to_exec_vmop;                 // total time in millis spent in vm operation itself
1242 };
1243 
1244 static const int _statistics_header_count = 30;
1245 static int _cur_stat_index = 0;
1246 static SafepointStats safepoint_stats = {0};  // zero initialize
1247 static SafepointStats* spstat = &safepoint_stats;
1248 
1249 static julong _safepoint_reasons[VM_Operation::VMOp_Terminating];
1250 static jlong  _max_sync_time = 0;
1251 static jlong  _max_vmop_time = 0;
1252 
1253 static jlong  cleanup_end_time = 0;
1254 
1255 void SafepointSynchronize::begin_statistics(int nof_threads, int nof_running) {
1256 
1257   spstat->_time_stamp = _ts_of_current_safepoint;
1258 
1259   VM_Operation *op = VMThread::vm_operation();
1260   spstat->_vmop_type = op != NULL ? op->type() : VM_Operation::VMOp_None;
1261   _safepoint_reasons[spstat->_vmop_type]++;
1262 
1263   spstat->_nof_total_threads = nof_threads;
1264   spstat->_nof_initial_running_threads = nof_running;
1265 
1266   // Records the start time of spinning. The real time spent on spinning
1267   // will be adjusted when spin is done. Same trick is applied for time
1268   // spent on waiting for threads to block.
1269   if (nof_running != 0) {
1270     spstat->_time_to_spin = os::javaTimeNanos();
1271   }  else {
1272     spstat->_time_to_spin = 0;
1273   }
1274 }
1275 
1276 void SafepointSynchronize::update_statistics_on_spin_end() {
1277   jlong cur_time = os::javaTimeNanos();
1278 
1279   spstat->_nof_threads_wait_to_block = _waiting_to_block;
1280   if (spstat->_nof_initial_running_threads != 0) {
1281     spstat->_time_to_spin = cur_time - spstat->_time_to_spin;
1282   }
1283 
1284   // Records the start time of waiting for to block. Updated when block is done.
1285   if (_waiting_to_block != 0) {
1286     spstat->_time_to_wait_to_block = cur_time;
1287   } else {
1288     spstat->_time_to_wait_to_block = 0;
1289   }
1290 }
1291 
1292 void SafepointSynchronize::update_statistics_on_sync_end(jlong end_time) {
1293 
1294   if (spstat->_nof_threads_wait_to_block != 0) {
1295     spstat->_time_to_wait_to_block = end_time -
1296       spstat->_time_to_wait_to_block;
1297   }
1298 
1299   // Records the end time of sync which will be used to calculate the total
1300   // vm operation time. Again, the real time spending in syncing will be deducted
1301   // from the start of the sync time later when end_statistics is called.
1302   spstat->_time_to_sync = end_time - _safepoint_begin_time;
1303   if (spstat->_time_to_sync > _max_sync_time) {
1304     _max_sync_time = spstat->_time_to_sync;
1305   }
1306 
1307   spstat->_time_to_do_cleanups = end_time;
1308 }
1309 
1310 void SafepointSynchronize::update_statistics_on_cleanup_end(jlong end_time) {
1311 
1312   // Record how long spent in cleanup tasks.
1313   spstat->_time_to_do_cleanups = end_time - spstat->_time_to_do_cleanups;
1314   cleanup_end_time = end_time;
1315 }
1316 
1317 void SafepointSynchronize::end_statistics(jlong vmop_end_time) {
1318 
1319   // Update the vm operation time.
1320   spstat->_time_to_exec_vmop = vmop_end_time -  cleanup_end_time;
1321   if (spstat->_time_to_exec_vmop > _max_vmop_time) {
1322     _max_vmop_time = spstat->_time_to_exec_vmop;
1323   }
1324 
1325   spstat->_nof_threads_hit_page_trap = _nof_threads_hit_polling_page;
1326 
1327   print_statistics();
1328 }
1329 
1330 // Helper method to print the header.
1331 static void print_header(outputStream* st) {
1332   // The number of spaces is significant here, and should match the format
1333   // specifiers in print_statistics().
1334 
1335   st->print("          vmop                            "
1336             "[ threads:    total initially_running wait_to_block ]"
1337             "[ time:    spin   block    sync cleanup    vmop ] ");
1338 
1339   st->print_cr("page_trap_count");
1340 }
1341 
1342 // This prints a nice table.  To get the statistics to not shift due to the logging uptime
1343 // decorator, use the option as: -Xlog:safepoint+stats=debug:[outputfile]:none
1344 void SafepointSynchronize::print_statistics() {
1345   LogTarget(Debug, safepoint, stats) lt;
1346   assert (lt.is_enabled(), "should only be called when printing statistics is enabled");
1347   LogStream ls(lt);
1348 
1349   // Print header every 30 entries
1350   if ((_cur_stat_index % _statistics_header_count) == 0) {
1351     print_header(&ls);
1352     _cur_stat_index = 1;  // wrap
1353   } else {
1354     _cur_stat_index++;
1355   }
1356 
1357   ls.print("%8.3f: ", spstat->_time_stamp);
1358   ls.print("%-28s  [          "
1359            INT32_FORMAT_W(8) " " INT32_FORMAT_W(17) " " INT32_FORMAT_W(13) " "
1360            "]",
1361            VM_Operation::name(spstat->_vmop_type),
1362            spstat->_nof_total_threads,
1363            spstat->_nof_initial_running_threads,
1364            spstat->_nof_threads_wait_to_block);
1365   // "/ MICROUNITS " is to convert the unit from nanos to millis.
1366   ls.print("[       "
1367            INT64_FORMAT_W(7) " " INT64_FORMAT_W(7) " "
1368            INT64_FORMAT_W(7) " " INT64_FORMAT_W(7) " "
1369            INT64_FORMAT_W(7) " ] ",
1370            (int64_t)(spstat->_time_to_spin / MICROUNITS),
1371            (int64_t)(spstat->_time_to_wait_to_block / MICROUNITS),
1372            (int64_t)(spstat->_time_to_sync / MICROUNITS),
1373            (int64_t)(spstat->_time_to_do_cleanups / MICROUNITS),
1374            (int64_t)(spstat->_time_to_exec_vmop / MICROUNITS));
1375 
1376   ls.print_cr(INT32_FORMAT_W(15) " ", spstat->_nof_threads_hit_page_trap);
1377 }
1378 
1379 // This method will be called when VM exits. This tries to summarize the sampling.
1380 // Current thread may already be deleted, so don't use ResourceMark.
1381 void SafepointSynchronize::print_stat_on_exit() {
1382 
1383   for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) {
1384     if (_safepoint_reasons[index] != 0) {
1385       log_debug(safepoint, stats)("%-28s" UINT64_FORMAT_W(10), VM_Operation::name(index),
1386                 _safepoint_reasons[index]);
1387     }
1388   }
1389 
1390   log_debug(safepoint, stats)("VM operations coalesced during safepoint " INT64_FORMAT,
1391                               _coalesced_vmop_count);
1392   log_debug(safepoint, stats)("Maximum sync time  " INT64_FORMAT" ms",
1393                               (int64_t)(_max_sync_time / MICROUNITS));
1394   log_debug(safepoint, stats)("Maximum vm operation time (except for Exit VM operation)  "
1395                               INT64_FORMAT " ms",
1396                               (int64_t)(_max_vmop_time / MICROUNITS));
1397 }