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