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