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