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