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