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