Fri, 06 Dec 2019 12:42:29 +0100
8235243: handle VS2017 15.9 and VS2019 in abstract_vm_version
8235325: build failure on Linux after 8235243
Reviewed-by: dholmes, mdoerr
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 TraceTime t8("rotating gc logs", TraceSafepointCleanupTime);
672 gclog_or_tty->rotate_log(false);
673 }
675 {
676 // CMS delays purging the CLDG until the beginning of the next safepoint and to
677 // make sure concurrent sweep is done
678 TraceTime t7("purging class loader data graph", TraceSafepointCleanupTime);
679 ClassLoaderDataGraph::purge_if_needed();
680 }
681 }
684 bool SafepointSynchronize::safepoint_safe(JavaThread *thread, JavaThreadState state) {
685 switch(state) {
686 case _thread_in_native:
687 // native threads are safe if they have no java stack or have walkable stack
688 return !thread->has_last_Java_frame() || thread->frame_anchor()->walkable();
690 // blocked threads should have already have walkable stack
691 case _thread_blocked:
692 assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "blocked and not walkable");
693 return true;
695 default:
696 return false;
697 }
698 }
701 // See if the thread is running inside a lazy critical native and
702 // update the thread critical count if so. Also set a suspend flag to
703 // cause the native wrapper to return into the JVM to do the unlock
704 // once the native finishes.
705 void SafepointSynchronize::check_for_lazy_critical_native(JavaThread *thread, JavaThreadState state) {
706 if (state == _thread_in_native &&
707 thread->has_last_Java_frame() &&
708 thread->frame_anchor()->walkable()) {
709 // This thread might be in a critical native nmethod so look at
710 // the top of the stack and increment the critical count if it
711 // is.
712 frame wrapper_frame = thread->last_frame();
713 CodeBlob* stub_cb = wrapper_frame.cb();
714 if (stub_cb != NULL &&
715 stub_cb->is_nmethod() &&
716 stub_cb->as_nmethod_or_null()->is_lazy_critical_native()) {
717 // A thread could potentially be in a critical native across
718 // more than one safepoint, so only update the critical state on
719 // the first one. When it returns it will perform the unlock.
720 if (!thread->do_critical_native_unlock()) {
721 #ifdef ASSERT
722 if (!thread->in_critical()) {
723 GC_locker::increment_debug_jni_lock_count();
724 }
725 #endif
726 thread->enter_critical();
727 // Make sure the native wrapper calls back on return to
728 // perform the needed critical unlock.
729 thread->set_critical_native_unlock();
730 }
731 }
732 }
733 }
737 // -------------------------------------------------------------------------------------------------------
738 // Implementation of Safepoint callback point
740 void SafepointSynchronize::block(JavaThread *thread) {
741 assert(thread != NULL, "thread must be set");
742 assert(thread->is_Java_thread(), "not a Java thread");
744 // Threads shouldn't block if they are in the middle of printing, but...
745 ttyLocker::break_tty_lock_for_safepoint(os::current_thread_id());
747 // Only bail from the block() call if the thread is gone from the
748 // thread list; starting to exit should still block.
749 if (thread->is_terminated()) {
750 // block current thread if we come here from native code when VM is gone
751 thread->block_if_vm_exited();
753 // otherwise do nothing
754 return;
755 }
757 JavaThreadState state = thread->thread_state();
758 thread->frame_anchor()->make_walkable(thread);
760 // Check that we have a valid thread_state at this point
761 switch(state) {
762 case _thread_in_vm_trans:
763 case _thread_in_Java: // From compiled code
765 // We are highly likely to block on the Safepoint_lock. In order to avoid blocking in this case,
766 // we pretend we are still in the VM.
767 thread->set_thread_state(_thread_in_vm);
769 if (is_synchronizing()) {
770 Atomic::inc (&TryingToBlock) ;
771 }
773 // We will always be holding the Safepoint_lock when we are examine the state
774 // of a thread. Hence, the instructions between the Safepoint_lock->lock() and
775 // Safepoint_lock->unlock() are happening atomic with regards to the safepoint code
776 Safepoint_lock->lock_without_safepoint_check();
777 if (is_synchronizing()) {
778 // Decrement the number of threads to wait for and signal vm thread
779 assert(_waiting_to_block > 0, "sanity check");
780 _waiting_to_block--;
781 thread->safepoint_state()->set_has_called_back(true);
783 DEBUG_ONLY(thread->set_visited_for_critical_count(true));
784 if (thread->in_critical()) {
785 // Notice that this thread is in a critical section
786 increment_jni_active_count();
787 }
789 // Consider (_waiting_to_block < 2) to pipeline the wakeup of the VM thread
790 if (_waiting_to_block == 0) {
791 Safepoint_lock->notify_all();
792 }
793 }
795 // We transition the thread to state _thread_blocked here, but
796 // we can't do our usual check for external suspension and then
797 // self-suspend after the lock_without_safepoint_check() call
798 // below because we are often called during transitions while
799 // we hold different locks. That would leave us suspended while
800 // holding a resource which results in deadlocks.
801 thread->set_thread_state(_thread_blocked);
802 Safepoint_lock->unlock();
804 // We now try to acquire the threads lock. Since this lock is hold by the VM thread during
805 // the entire safepoint, the threads will all line up here during the safepoint.
806 Threads_lock->lock_without_safepoint_check();
807 // restore original state. This is important if the thread comes from compiled code, so it
808 // will continue to execute with the _thread_in_Java state.
809 thread->set_thread_state(state);
810 Threads_lock->unlock();
811 break;
813 case _thread_in_native_trans:
814 case _thread_blocked_trans:
815 case _thread_new_trans:
816 if (thread->safepoint_state()->type() == ThreadSafepointState::_call_back) {
817 thread->print_thread_state();
818 fatal("Deadlock in safepoint code. "
819 "Should have called back to the VM before blocking.");
820 }
822 // We transition the thread to state _thread_blocked here, but
823 // we can't do our usual check for external suspension and then
824 // self-suspend after the lock_without_safepoint_check() call
825 // below because we are often called during transitions while
826 // we hold different locks. That would leave us suspended while
827 // holding a resource which results in deadlocks.
828 thread->set_thread_state(_thread_blocked);
830 // It is not safe to suspend a thread if we discover it is in _thread_in_native_trans. Hence,
831 // the safepoint code might still be waiting for it to block. We need to change the state here,
832 // so it can see that it is at a safepoint.
834 // Block until the safepoint operation is completed.
835 Threads_lock->lock_without_safepoint_check();
837 // Restore state
838 thread->set_thread_state(state);
840 Threads_lock->unlock();
841 break;
843 default:
844 fatal(err_msg("Illegal threadstate encountered: %d", state));
845 }
847 // Check for pending. async. exceptions or suspends - except if the
848 // thread was blocked inside the VM. has_special_runtime_exit_condition()
849 // is called last since it grabs a lock and we only want to do that when
850 // we must.
851 //
852 // Note: we never deliver an async exception at a polling point as the
853 // compiler may not have an exception handler for it. The polling
854 // code will notice the async and deoptimize and the exception will
855 // be delivered. (Polling at a return point is ok though). Sure is
856 // a lot of bother for a deprecated feature...
857 //
858 // We don't deliver an async exception if the thread state is
859 // _thread_in_native_trans so JNI functions won't be called with
860 // a surprising pending exception. If the thread state is going back to java,
861 // async exception is checked in check_special_condition_for_native_trans().
863 if (state != _thread_blocked_trans &&
864 state != _thread_in_vm_trans &&
865 thread->has_special_runtime_exit_condition()) {
866 thread->handle_special_runtime_exit_condition(
867 !thread->is_at_poll_safepoint() && (state != _thread_in_native_trans));
868 }
869 }
871 // ------------------------------------------------------------------------------------------------------
872 // Exception handlers
875 void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
876 assert(thread->is_Java_thread(), "polling reference encountered by VM thread");
877 assert(thread->thread_state() == _thread_in_Java, "should come from Java code");
878 assert(SafepointSynchronize::is_synchronizing(), "polling encountered outside safepoint synchronization");
880 if (ShowSafepointMsgs) {
881 tty->print("handle_polling_page_exception: ");
882 }
884 if (PrintSafepointStatistics) {
885 inc_page_trap_count();
886 }
888 ThreadSafepointState* state = thread->safepoint_state();
890 state->handle_polling_page_exception();
891 }
894 void SafepointSynchronize::print_safepoint_timeout(SafepointTimeoutReason reason) {
895 if (!timeout_error_printed) {
896 timeout_error_printed = true;
897 // Print out the thread infor which didn't reach the safepoint for debugging
898 // purposes (useful when there are lots of threads in the debugger).
899 tty->cr();
900 tty->print_cr("# SafepointSynchronize::begin: Timeout detected:");
901 if (reason == _spinning_timeout) {
902 tty->print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint.");
903 } else if (reason == _blocking_timeout) {
904 tty->print_cr("# SafepointSynchronize::begin: Timed out while waiting for threads to stop.");
905 }
907 tty->print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:");
908 ThreadSafepointState *cur_state;
909 ResourceMark rm;
910 for(JavaThread *cur_thread = Threads::first(); cur_thread;
911 cur_thread = cur_thread->next()) {
912 cur_state = cur_thread->safepoint_state();
914 if (cur_thread->thread_state() != _thread_blocked &&
915 ((reason == _spinning_timeout && cur_state->is_running()) ||
916 (reason == _blocking_timeout && !cur_state->has_called_back()))) {
917 tty->print("# ");
918 cur_thread->print();
919 tty->cr();
920 }
921 }
922 tty->print_cr("# SafepointSynchronize::begin: (End of list)");
923 }
925 // To debug the long safepoint, specify both AbortVMOnSafepointTimeout &
926 // ShowMessageBoxOnError.
927 if (AbortVMOnSafepointTimeout) {
928 char msg[1024];
929 VM_Operation *op = VMThread::vm_operation();
930 sprintf(msg, "Safepoint sync time longer than " INTX_FORMAT "ms detected when executing %s.",
931 SafepointTimeoutDelay,
932 op != NULL ? op->name() : "no vm operation");
933 fatal(msg);
934 }
935 }
938 // -------------------------------------------------------------------------------------------------------
939 // Implementation of ThreadSafepointState
941 ThreadSafepointState::ThreadSafepointState(JavaThread *thread) {
942 _thread = thread;
943 _type = _running;
944 _has_called_back = false;
945 _at_poll_safepoint = false;
946 }
948 void ThreadSafepointState::create(JavaThread *thread) {
949 ThreadSafepointState *state = new ThreadSafepointState(thread);
950 thread->set_safepoint_state(state);
951 }
953 void ThreadSafepointState::destroy(JavaThread *thread) {
954 if (thread->safepoint_state()) {
955 delete(thread->safepoint_state());
956 thread->set_safepoint_state(NULL);
957 }
958 }
960 void ThreadSafepointState::examine_state_of_thread() {
961 assert(is_running(), "better be running or just have hit safepoint poll");
963 JavaThreadState state = _thread->thread_state();
965 // Save the state at the start of safepoint processing.
966 _orig_thread_state = state;
968 // Check for a thread that is suspended. Note that thread resume tries
969 // to grab the Threads_lock which we own here, so a thread cannot be
970 // resumed during safepoint synchronization.
972 // We check to see if this thread is suspended without locking to
973 // avoid deadlocking with a third thread that is waiting for this
974 // thread to be suspended. The third thread can notice the safepoint
975 // that we're trying to start at the beginning of its SR_lock->wait()
976 // call. If that happens, then the third thread will block on the
977 // safepoint while still holding the underlying SR_lock. We won't be
978 // able to get the SR_lock and we'll deadlock.
979 //
980 // We don't need to grab the SR_lock here for two reasons:
981 // 1) The suspend flags are both volatile and are set with an
982 // Atomic::cmpxchg() call so we should see the suspended
983 // state right away.
984 // 2) We're being called from the safepoint polling loop; if
985 // we don't see the suspended state on this iteration, then
986 // we'll come around again.
987 //
988 bool is_suspended = _thread->is_ext_suspended();
989 if (is_suspended) {
990 roll_forward(_at_safepoint);
991 return;
992 }
994 // Some JavaThread states have an initial safepoint state of
995 // running, but are actually at a safepoint. We will happily
996 // agree and update the safepoint state here.
997 if (SafepointSynchronize::safepoint_safe(_thread, state)) {
998 SafepointSynchronize::check_for_lazy_critical_native(_thread, state);
999 roll_forward(_at_safepoint);
1000 return;
1001 }
1003 if (state == _thread_in_vm) {
1004 roll_forward(_call_back);
1005 return;
1006 }
1008 // All other thread states will continue to run until they
1009 // transition and self-block in state _blocked
1010 // Safepoint polling in compiled code causes the Java threads to do the same.
1011 // Note: new threads may require a malloc so they must be allowed to finish
1013 assert(is_running(), "examine_state_of_thread on non-running thread");
1014 return;
1015 }
1017 // Returns true is thread could not be rolled forward at present position.
1018 void ThreadSafepointState::roll_forward(suspend_type type) {
1019 _type = type;
1021 switch(_type) {
1022 case _at_safepoint:
1023 SafepointSynchronize::signal_thread_at_safepoint();
1024 DEBUG_ONLY(_thread->set_visited_for_critical_count(true));
1025 if (_thread->in_critical()) {
1026 // Notice that this thread is in a critical section
1027 SafepointSynchronize::increment_jni_active_count();
1028 }
1029 break;
1031 case _call_back:
1032 set_has_called_back(false);
1033 break;
1035 case _running:
1036 default:
1037 ShouldNotReachHere();
1038 }
1039 }
1041 void ThreadSafepointState::restart() {
1042 switch(type()) {
1043 case _at_safepoint:
1044 case _call_back:
1045 break;
1047 case _running:
1048 default:
1049 tty->print_cr("restart thread " INTPTR_FORMAT " with state %d",
1050 _thread, _type);
1051 _thread->print();
1052 ShouldNotReachHere();
1053 }
1054 _type = _running;
1055 set_has_called_back(false);
1056 }
1059 void ThreadSafepointState::print_on(outputStream *st) const {
1060 const char *s = NULL;
1062 switch(_type) {
1063 case _running : s = "_running"; break;
1064 case _at_safepoint : s = "_at_safepoint"; break;
1065 case _call_back : s = "_call_back"; break;
1066 default:
1067 ShouldNotReachHere();
1068 }
1070 st->print_cr("Thread: " INTPTR_FORMAT
1071 " [0x%2x] State: %s _has_called_back %d _at_poll_safepoint %d",
1072 _thread, _thread->osthread()->thread_id(), s, _has_called_back,
1073 _at_poll_safepoint);
1075 _thread->print_thread_state_on(st);
1076 }
1079 // ---------------------------------------------------------------------------------------------------------------------
1081 // Block the thread at the safepoint poll or poll return.
1082 void ThreadSafepointState::handle_polling_page_exception() {
1084 // Check state. block() will set thread state to thread_in_vm which will
1085 // cause the safepoint state _type to become _call_back.
1086 assert(type() == ThreadSafepointState::_running,
1087 "polling page exception on thread not running state");
1089 // Step 1: Find the nmethod from the return address
1090 if (ShowSafepointMsgs && Verbose) {
1091 tty->print_cr("Polling page exception at " INTPTR_FORMAT, thread()->saved_exception_pc());
1092 }
1093 address real_return_addr = thread()->saved_exception_pc();
1095 CodeBlob *cb = CodeCache::find_blob(real_return_addr);
1096 assert(cb != NULL && cb->is_nmethod(), "return address should be in nmethod");
1097 nmethod* nm = (nmethod*)cb;
1099 // Find frame of caller
1100 frame stub_fr = thread()->last_frame();
1101 CodeBlob* stub_cb = stub_fr.cb();
1102 assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub");
1103 RegisterMap map(thread(), true);
1104 frame caller_fr = stub_fr.sender(&map);
1106 // Should only be poll_return or poll
1107 assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" );
1109 // This is a poll immediately before a return. The exception handling code
1110 // has already had the effect of causing the return to occur, so the execution
1111 // will continue immediately after the call. In addition, the oopmap at the
1112 // return point does not mark the return value as an oop (if it is), so
1113 // it needs a handle here to be updated.
1114 if( nm->is_at_poll_return(real_return_addr) ) {
1115 // See if return type is an oop.
1116 bool return_oop = nm->method()->is_returning_oop();
1117 Handle return_value;
1118 if (return_oop) {
1119 // The oop result has been saved on the stack together with all
1120 // the other registers. In order to preserve it over GCs we need
1121 // to keep it in a handle.
1122 oop result = caller_fr.saved_oop_result(&map);
1123 assert(result == NULL || result->is_oop(), "must be oop");
1124 return_value = Handle(thread(), result);
1125 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
1126 }
1128 // Block the thread
1129 SafepointSynchronize::block(thread());
1131 // restore oop result, if any
1132 if (return_oop) {
1133 caller_fr.set_saved_oop_result(&map, return_value());
1134 }
1135 }
1137 // This is a safepoint poll. Verify the return address and block.
1138 else {
1139 set_at_poll_safepoint(true);
1141 // verify the blob built the "return address" correctly
1142 assert(real_return_addr == caller_fr.pc(), "must match");
1144 // Block the thread
1145 SafepointSynchronize::block(thread());
1146 set_at_poll_safepoint(false);
1148 // If we have a pending async exception deoptimize the frame
1149 // as otherwise we may never deliver it.
1150 if (thread()->has_async_condition()) {
1151 ThreadInVMfromJavaNoAsyncException __tiv(thread());
1152 Deoptimization::deoptimize_frame(thread(), caller_fr.id());
1153 }
1155 // If an exception has been installed we must check for a pending deoptimization
1156 // Deoptimize frame if exception has been thrown.
1158 if (thread()->has_pending_exception() ) {
1159 RegisterMap map(thread(), true);
1160 frame caller_fr = stub_fr.sender(&map);
1161 if (caller_fr.is_deoptimized_frame()) {
1162 // The exception patch will destroy registers that are still
1163 // live and will be needed during deoptimization. Defer the
1164 // Async exception should have defered the exception until the
1165 // next safepoint which will be detected when we get into
1166 // the interpreter so if we have an exception now things
1167 // are messed up.
1169 fatal("Exception installed and deoptimization is pending");
1170 }
1171 }
1172 }
1173 }
1176 //
1177 // Statistics & Instrumentations
1178 //
1179 SafepointSynchronize::SafepointStats* SafepointSynchronize::_safepoint_stats = NULL;
1180 jlong SafepointSynchronize::_safepoint_begin_time = 0;
1181 int SafepointSynchronize::_cur_stat_index = 0;
1182 julong SafepointSynchronize::_safepoint_reasons[VM_Operation::VMOp_Terminating];
1183 julong SafepointSynchronize::_coalesced_vmop_count = 0;
1184 jlong SafepointSynchronize::_max_sync_time = 0;
1185 jlong SafepointSynchronize::_max_vmop_time = 0;
1186 float SafepointSynchronize::_ts_of_current_safepoint = 0.0f;
1188 static jlong cleanup_end_time = 0;
1189 static bool need_to_track_page_armed_status = false;
1190 static bool init_done = false;
1192 // Helper method to print the header.
1193 static void print_header() {
1194 tty->print(" vmop "
1195 "[threads: total initially_running wait_to_block] ");
1196 tty->print("[time: spin block sync cleanup vmop] ");
1198 // no page armed status printed out if it is always armed.
1199 if (need_to_track_page_armed_status) {
1200 tty->print("page_armed ");
1201 }
1203 tty->print_cr("page_trap_count");
1204 }
1206 void SafepointSynchronize::deferred_initialize_stat() {
1207 if (init_done) return;
1209 if (PrintSafepointStatisticsCount <= 0) {
1210 fatal("Wrong PrintSafepointStatisticsCount");
1211 }
1213 // If PrintSafepointStatisticsTimeout is specified, the statistics data will
1214 // be printed right away, in which case, _safepoint_stats will regress to
1215 // a single element array. Otherwise, it is a circular ring buffer with default
1216 // size of PrintSafepointStatisticsCount.
1217 int stats_array_size;
1218 if (PrintSafepointStatisticsTimeout > 0) {
1219 stats_array_size = 1;
1220 PrintSafepointStatistics = true;
1221 } else {
1222 stats_array_size = PrintSafepointStatisticsCount;
1223 }
1224 _safepoint_stats = (SafepointStats*)os::malloc(stats_array_size
1225 * sizeof(SafepointStats), mtInternal);
1226 guarantee(_safepoint_stats != NULL,
1227 "not enough memory for safepoint instrumentation data");
1229 if (UseCompilerSafepoints && DeferPollingPageLoopCount >= 0) {
1230 need_to_track_page_armed_status = true;
1231 }
1232 init_done = true;
1233 }
1235 void SafepointSynchronize::begin_statistics(int nof_threads, int nof_running) {
1236 assert(init_done, "safepoint statistics array hasn't been initialized");
1237 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1239 spstat->_time_stamp = _ts_of_current_safepoint;
1241 VM_Operation *op = VMThread::vm_operation();
1242 spstat->_vmop_type = (op != NULL ? op->type() : -1);
1243 if (op != NULL) {
1244 _safepoint_reasons[spstat->_vmop_type]++;
1245 }
1247 spstat->_nof_total_threads = nof_threads;
1248 spstat->_nof_initial_running_threads = nof_running;
1249 spstat->_nof_threads_hit_page_trap = 0;
1251 // Records the start time of spinning. The real time spent on spinning
1252 // will be adjusted when spin is done. Same trick is applied for time
1253 // spent on waiting for threads to block.
1254 if (nof_running != 0) {
1255 spstat->_time_to_spin = os::javaTimeNanos();
1256 } else {
1257 spstat->_time_to_spin = 0;
1258 }
1259 }
1261 void SafepointSynchronize::update_statistics_on_spin_end() {
1262 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1264 jlong cur_time = os::javaTimeNanos();
1266 spstat->_nof_threads_wait_to_block = _waiting_to_block;
1267 if (spstat->_nof_initial_running_threads != 0) {
1268 spstat->_time_to_spin = cur_time - spstat->_time_to_spin;
1269 }
1271 if (need_to_track_page_armed_status) {
1272 spstat->_page_armed = (PageArmed == 1);
1273 }
1275 // Records the start time of waiting for to block. Updated when block is done.
1276 if (_waiting_to_block != 0) {
1277 spstat->_time_to_wait_to_block = cur_time;
1278 } else {
1279 spstat->_time_to_wait_to_block = 0;
1280 }
1281 }
1283 void SafepointSynchronize::update_statistics_on_sync_end(jlong end_time) {
1284 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1286 if (spstat->_nof_threads_wait_to_block != 0) {
1287 spstat->_time_to_wait_to_block = end_time -
1288 spstat->_time_to_wait_to_block;
1289 }
1291 // Records the end time of sync which will be used to calculate the total
1292 // vm operation time. Again, the real time spending in syncing will be deducted
1293 // from the start of the sync time later when end_statistics is called.
1294 spstat->_time_to_sync = end_time - _safepoint_begin_time;
1295 if (spstat->_time_to_sync > _max_sync_time) {
1296 _max_sync_time = spstat->_time_to_sync;
1297 }
1299 spstat->_time_to_do_cleanups = end_time;
1300 }
1302 void SafepointSynchronize::update_statistics_on_cleanup_end(jlong end_time) {
1303 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1305 // Record how long spent in cleanup tasks.
1306 spstat->_time_to_do_cleanups = end_time - spstat->_time_to_do_cleanups;
1308 cleanup_end_time = end_time;
1309 }
1311 void SafepointSynchronize::end_statistics(jlong vmop_end_time) {
1312 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1314 // Update the vm operation time.
1315 spstat->_time_to_exec_vmop = vmop_end_time - cleanup_end_time;
1316 if (spstat->_time_to_exec_vmop > _max_vmop_time) {
1317 _max_vmop_time = spstat->_time_to_exec_vmop;
1318 }
1319 // Only the sync time longer than the specified
1320 // PrintSafepointStatisticsTimeout will be printed out right away.
1321 // By default, it is -1 meaning all samples will be put into the list.
1322 if ( PrintSafepointStatisticsTimeout > 0) {
1323 if (spstat->_time_to_sync > PrintSafepointStatisticsTimeout * MICROUNITS) {
1324 print_statistics();
1325 }
1326 } else {
1327 // The safepoint statistics will be printed out when the _safepoin_stats
1328 // array fills up.
1329 if (_cur_stat_index == PrintSafepointStatisticsCount - 1) {
1330 print_statistics();
1331 _cur_stat_index = 0;
1332 } else {
1333 _cur_stat_index++;
1334 }
1335 }
1336 }
1338 void SafepointSynchronize::print_statistics() {
1339 SafepointStats* sstats = _safepoint_stats;
1341 for (int index = 0; index <= _cur_stat_index; index++) {
1342 if (index % 30 == 0) {
1343 print_header();
1344 }
1345 sstats = &_safepoint_stats[index];
1346 tty->print("%.3f: ", sstats->_time_stamp);
1347 tty->print("%-26s ["
1348 INT32_FORMAT_W(8) INT32_FORMAT_W(11) INT32_FORMAT_W(15)
1349 " ] ",
1350 sstats->_vmop_type == -1 ? "no vm operation" :
1351 VM_Operation::name(sstats->_vmop_type),
1352 sstats->_nof_total_threads,
1353 sstats->_nof_initial_running_threads,
1354 sstats->_nof_threads_wait_to_block);
1355 // "/ MICROUNITS " is to convert the unit from nanos to millis.
1356 tty->print(" ["
1357 INT64_FORMAT_W(6) INT64_FORMAT_W(6)
1358 INT64_FORMAT_W(6) INT64_FORMAT_W(6)
1359 INT64_FORMAT_W(6) " ] ",
1360 sstats->_time_to_spin / MICROUNITS,
1361 sstats->_time_to_wait_to_block / MICROUNITS,
1362 sstats->_time_to_sync / MICROUNITS,
1363 sstats->_time_to_do_cleanups / MICROUNITS,
1364 sstats->_time_to_exec_vmop / MICROUNITS);
1366 if (need_to_track_page_armed_status) {
1367 tty->print(INT32_FORMAT " ", sstats->_page_armed);
1368 }
1369 tty->print_cr(INT32_FORMAT " ", sstats->_nof_threads_hit_page_trap);
1370 }
1371 }
1373 // This method will be called when VM exits. It will first call
1374 // print_statistics to print out the rest of the sampling. Then
1375 // it tries to summarize the sampling.
1376 void SafepointSynchronize::print_stat_on_exit() {
1377 if (_safepoint_stats == NULL) return;
1379 SafepointStats *spstat = &_safepoint_stats[_cur_stat_index];
1381 // During VM exit, end_statistics may not get called and in that
1382 // case, if the sync time is less than PrintSafepointStatisticsTimeout,
1383 // don't print it out.
1384 // Approximate the vm op time.
1385 _safepoint_stats[_cur_stat_index]._time_to_exec_vmop =
1386 os::javaTimeNanos() - cleanup_end_time;
1388 if ( PrintSafepointStatisticsTimeout < 0 ||
1389 spstat->_time_to_sync > PrintSafepointStatisticsTimeout * MICROUNITS) {
1390 print_statistics();
1391 }
1392 tty->cr();
1394 // Print out polling page sampling status.
1395 if (!need_to_track_page_armed_status) {
1396 if (UseCompilerSafepoints) {
1397 tty->print_cr("Polling page always armed");
1398 }
1399 } else {
1400 tty->print_cr("Defer polling page loop count = %d\n",
1401 DeferPollingPageLoopCount);
1402 }
1404 for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) {
1405 if (_safepoint_reasons[index] != 0) {
1406 tty->print_cr("%-26s" UINT64_FORMAT_W(10), VM_Operation::name(index),
1407 _safepoint_reasons[index]);
1408 }
1409 }
1411 tty->print_cr(UINT64_FORMAT_W(5) " VM operations coalesced during safepoint",
1412 _coalesced_vmop_count);
1413 tty->print_cr("Maximum sync time " INT64_FORMAT_W(5) " ms",
1414 _max_sync_time / MICROUNITS);
1415 tty->print_cr("Maximum vm operation time (except for Exit VM operation) "
1416 INT64_FORMAT_W(5) " ms",
1417 _max_vmop_time / MICROUNITS);
1418 }
1420 // ------------------------------------------------------------------------------------------------
1421 // Non-product code
1423 #ifndef PRODUCT
1425 void SafepointSynchronize::print_state() {
1426 if (_state == _not_synchronized) {
1427 tty->print_cr("not synchronized");
1428 } else if (_state == _synchronizing || _state == _synchronized) {
1429 tty->print_cr("State: %s", (_state == _synchronizing) ? "synchronizing" :
1430 "synchronized");
1432 for(JavaThread *cur = Threads::first(); cur; cur = cur->next()) {
1433 cur->safepoint_state()->print();
1434 }
1435 }
1436 }
1438 void SafepointSynchronize::safepoint_msg(const char* format, ...) {
1439 if (ShowSafepointMsgs) {
1440 va_list ap;
1441 va_start(ap, format);
1442 tty->vprint_cr(format, ap);
1443 va_end(ap);
1444 }
1445 }
1447 #endif // !PRODUCT