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