1 /*
2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "code/codeCache.hpp"
26 #include "code/nmethod.hpp"
27 #include "code/pcDesc.hpp"
28 #include "code/scopeDesc.hpp"
29 #include "compiler/compilationPolicy.hpp"
30 #include "gc/shared/collectedHeap.hpp"
31 #include "gc/shared/gcLocker.hpp"
32 #include "gc/shared/oopStorage.hpp"
33 #include "gc/shared/workerThread.hpp"
34 #include "gc/shared/workerUtils.hpp"
35 #include "interpreter/interpreter.hpp"
36 #include "jfr/jfrEvents.hpp"
37 #include "logging/log.hpp"
38 #include "logging/logStream.hpp"
39 #include "memory/resourceArea.hpp"
40 #include "memory/universe.hpp"
41 #include "oops/inlineKlass.hpp"
42 #include "oops/oop.inline.hpp"
43 #include "oops/symbol.hpp"
44 #include "runtime/atomicAccess.hpp"
45 #include "runtime/deoptimization.hpp"
46 #include "runtime/frame.inline.hpp"
47 #include "runtime/globals.hpp"
48 #include "runtime/handles.inline.hpp"
49 #include "runtime/interfaceSupport.inline.hpp"
50 #include "runtime/javaThread.inline.hpp"
51 #include "runtime/mutexLocker.hpp"
52 #include "runtime/orderAccess.hpp"
53 #include "runtime/osThread.hpp"
54 #include "runtime/safepoint.hpp"
55 #include "runtime/safepointMechanism.inline.hpp"
56 #include "runtime/signature.hpp"
57 #include "runtime/stackWatermarkSet.inline.hpp"
58 #include "runtime/stubCodeGenerator.hpp"
59 #include "runtime/stubRoutines.hpp"
60 #include "runtime/synchronizer.hpp"
61 #include "runtime/threads.hpp"
62 #include "runtime/threadSMR.hpp"
63 #include "runtime/threadWXSetters.inline.hpp"
64 #include "runtime/timerTrace.hpp"
65 #include "services/runtimeService.hpp"
66 #include "utilities/events.hpp"
67 #include "utilities/macros.hpp"
68 #include "utilities/systemMemoryBarrier.hpp"
69 #include "utilities/vmError.hpp"
70
71 static void post_safepoint_begin_event(EventSafepointBegin& event,
72 uint64_t safepoint_id,
73 int thread_count,
74 int critical_thread_count) {
75 if (event.should_commit()) {
76 event.set_safepointId(safepoint_id);
77 event.set_totalThreadCount(thread_count);
78 event.set_jniCriticalThreadCount(critical_thread_count);
79 event.commit();
80 }
81 }
82
83
84 static void post_safepoint_synchronize_event(EventSafepointStateSynchronization& event,
85 uint64_t safepoint_id,
86 int initial_number_of_threads,
87 int threads_waiting_to_block,
88 int iterations) {
89 if (event.should_commit()) {
90 event.set_safepointId(safepoint_id);
91 event.set_initialThreadCount(initial_number_of_threads);
92 event.set_runningThreadCount(threads_waiting_to_block);
93 event.set_iterations(checked_cast<u4>(iterations));
94 event.commit();
95 }
96 }
97
98 static void post_safepoint_end_event(EventSafepointEnd& event, uint64_t safepoint_id) {
99 if (event.should_commit()) {
100 event.set_safepointId(safepoint_id);
101 event.commit();
102 }
103 }
104
105 // SafepointCheck
106 SafepointStateTracker::SafepointStateTracker(uint64_t safepoint_id, bool at_safepoint)
107 : _safepoint_id(safepoint_id), _at_safepoint(at_safepoint) {}
108
109 bool SafepointStateTracker::safepoint_state_changed() {
110 return _safepoint_id != SafepointSynchronize::safepoint_id() ||
111 _at_safepoint != SafepointSynchronize::is_at_safepoint();
112 }
113
114 // --------------------------------------------------------------------------------------------------
115 // Implementation of Safepoint begin/end
116
117 SafepointSynchronize::SynchronizeState volatile SafepointSynchronize::_state = SafepointSynchronize::_not_synchronized;
118 int SafepointSynchronize::_waiting_to_block = 0;
119 volatile uint64_t SafepointSynchronize::_safepoint_counter = 0;
120 uint64_t SafepointSynchronize::_safepoint_id = 0;
121 const uint64_t SafepointSynchronize::InactiveSafepointCounter = 0;
122 int SafepointSynchronize::_current_jni_active_count = 0;
123
124 WaitBarrier* SafepointSynchronize::_wait_barrier;
125
126 static bool timeout_error_printed = false;
127
128 // Statistic related
129 static jlong _safepoint_begin_time = 0;
130 static volatile int _nof_threads_hit_polling_page = 0;
131
132 void SafepointSynchronize::init(Thread* vmthread) {
133 // WaitBarrier should never be destroyed since we will have
134 // threads waiting on it while exiting.
135 _wait_barrier = new WaitBarrier(vmthread);
136 SafepointTracing::init();
137 }
138
139 void SafepointSynchronize::increment_jni_active_count() {
140 assert(Thread::current()->is_VM_thread(), "Only VM thread may increment");
141 ++_current_jni_active_count;
142 }
143
144 void SafepointSynchronize::decrement_waiting_to_block() {
145 assert(_waiting_to_block > 0, "sanity check");
146 assert(Thread::current()->is_VM_thread(), "Only VM thread may decrement");
147 --_waiting_to_block;
148 }
149
150 bool SafepointSynchronize::thread_not_running(ThreadSafepointState *cur_state) {
151 if (!cur_state->is_running()) {
152 // Robustness: asserted in the caller, but handle/tolerate it for release bits.
153 LogTarget(Error, safepoint) lt;
154 if (lt.is_enabled()) {
155 LogStream ls(lt);
156 ls.print("Illegal initial state detected: ");
157 cur_state->print_on(&ls);
158 }
159 return true;
160 }
161 cur_state->examine_state_of_thread(SafepointSynchronize::safepoint_counter());
162 if (!cur_state->is_running()) {
163 return true;
164 }
165 LogTarget(Trace, safepoint) lt;
166 if (lt.is_enabled()) {
167 LogStream ls(lt);
168 cur_state->print_on(&ls);
169 }
170 return false;
171 }
172
173 #ifdef ASSERT
174 static void assert_list_is_valid(const ThreadSafepointState* tss_head, int still_running) {
175 int a = 0;
176 const ThreadSafepointState *tmp_tss = tss_head;
177 while (tmp_tss != nullptr) {
178 ++a;
179 assert(tmp_tss->is_running(), "Illegal initial state");
180 tmp_tss = tmp_tss->get_next();
181 }
182 assert(a == still_running, "Must be the same");
183 }
184 #endif // ASSERT
185
186 static void back_off(int64_t start_time) {
187 // We start with fine-grained nanosleeping until a millisecond has
188 // passed, at which point we resort to plain naked_short_sleep.
189 if (os::javaTimeNanos() - start_time < NANOSECS_PER_MILLISEC) {
190 os::naked_short_nanosleep(10 * (NANOUNITS / MICROUNITS));
191 } else {
192 os::naked_short_sleep(1);
193 }
194 }
195
196 int SafepointSynchronize::synchronize_threads(jlong safepoint_limit_time, int nof_threads, int* initial_running)
197 {
198 JavaThreadIteratorWithHandle jtiwh;
199
200 #ifdef ASSERT
201 for (; JavaThread *cur = jtiwh.next(); ) {
202 assert(cur->safepoint_state()->is_running(), "Illegal initial state");
203 }
204 jtiwh.rewind();
205 #endif // ASSERT
206
207 // Iterate through all threads until it has been determined how to stop them all at a safepoint.
208 int still_running = nof_threads;
209 ThreadSafepointState *tss_head = nullptr;
210 ThreadSafepointState **p_prev = &tss_head;
211 for (; JavaThread *cur = jtiwh.next(); ) {
212 ThreadSafepointState *cur_tss = cur->safepoint_state();
213 assert(cur_tss->get_next() == nullptr, "Must be null");
214 if (thread_not_running(cur_tss)) {
215 --still_running;
216 } else {
217 *p_prev = cur_tss;
218 p_prev = cur_tss->next_ptr();
219 }
220 }
221 *p_prev = nullptr;
222
223 DEBUG_ONLY(assert_list_is_valid(tss_head, still_running);)
224
225 *initial_running = still_running;
226
227 // If there is no thread still running, we are already done.
228 if (still_running <= 0) {
229 assert(tss_head == nullptr, "Must be empty");
230 return 1;
231 }
232
233 int iterations = 1; // The first iteration is above.
234 int64_t start_time = os::javaTimeNanos();
235
236 do {
237 // Check if this has taken too long:
238 if (SafepointTimeout && safepoint_limit_time < os::javaTimeNanos()) {
239 print_safepoint_timeout();
240 }
241
242 p_prev = &tss_head;
243 ThreadSafepointState *cur_tss = tss_head;
244 while (cur_tss != nullptr) {
245 assert(cur_tss->is_running(), "Illegal initial state");
246 if (thread_not_running(cur_tss)) {
247 --still_running;
248 *p_prev = nullptr;
249 ThreadSafepointState *tmp = cur_tss;
250 cur_tss = cur_tss->get_next();
251 tmp->set_next(nullptr);
252 } else {
253 *p_prev = cur_tss;
254 p_prev = cur_tss->next_ptr();
255 cur_tss = cur_tss->get_next();
256 }
257 }
258
259 DEBUG_ONLY(assert_list_is_valid(tss_head, still_running);)
260
261 if (still_running > 0) {
262 back_off(start_time);
263 }
264
265 iterations++;
266 } while (still_running > 0);
267
268 assert(tss_head == nullptr, "Must be empty");
269
270 return iterations;
271 }
272
273 void SafepointSynchronize::arm_safepoint() {
274 // Begin the process of bringing the system to a safepoint.
275 // Java threads can be in several different states and are
276 // stopped by different mechanisms:
277 //
278 // 1. Running interpreted
279 // When executing branching/returning byte codes interpreter
280 // checks if the poll is armed, if so blocks in SS::block().
281 // 2. Running in native code
282 // When returning from the native code, a Java thread must check
283 // the safepoint _state to see if we must block. If the
284 // VM thread sees a Java thread in native, it does
285 // not wait for this thread to block. The order of the memory
286 // writes and reads of both the safepoint state and the Java
287 // threads state is critical. In order to guarantee that the
288 // memory writes are serialized with respect to each other,
289 // the VM thread issues a memory barrier instruction.
290 // 3. Running compiled Code
291 // Compiled code reads the local polling page that
292 // is set to fault if we are trying to get to a safepoint.
293 // 4. Blocked
294 // A thread which is blocked will not be allowed to return from the
295 // block condition until the safepoint operation is complete.
296 // 5. In VM or Transitioning between states
297 // If a Java thread is currently running in the VM or transitioning
298 // between states, the safepointing code will poll the thread state
299 // until the thread blocks itself when it attempts transitions to a
300 // new state or locking a safepoint checked monitor.
301
302 // We must never miss a thread with correct safepoint id, so we must make sure we arm
303 // the wait barrier for the next safepoint id/counter.
304 // Arming must be done after resetting _current_jni_active_count, _waiting_to_block.
305 _wait_barrier->arm(static_cast<int>(_safepoint_counter + 1));
306
307 assert((_safepoint_counter & 0x1) == 0, "must be even");
308 // The store to _safepoint_counter must happen after any stores in arming.
309 AtomicAccess::release_store(&_safepoint_counter, _safepoint_counter + 1);
310
311 // We are synchronizing
312 OrderAccess::storestore(); // Ordered with _safepoint_counter
313 _state = _synchronizing;
314
315 // Arming the per thread poll while having _state != _not_synchronized means safepointing
316 log_trace(safepoint)("Setting thread local yield flag for threads");
317 OrderAccess::storestore(); // storestore, global state -> local state
318 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur = jtiwh.next(); ) {
319 // Make sure the threads start polling, it is time to yield.
320 SafepointMechanism::arm_local_poll(cur);
321 }
322 if (UseSystemMemoryBarrier) {
323 SystemMemoryBarrier::emit(); // storestore|storeload, global state -> local state
324 } else {
325 OrderAccess::fence(); // storestore|storeload, global state -> local state
326 }
327 }
328
329 // Roll all threads forward to a safepoint and suspend them all
330 void SafepointSynchronize::begin() {
331 assert(Thread::current()->is_VM_thread(), "Only VM thread may execute a safepoint");
332
333 EventSafepointBegin begin_event;
334 SafepointTracing::begin(VMThread::vm_op_type());
335
336 Universe::heap()->safepoint_synchronize_begin();
337
338 // By getting the Threads_lock, we assure that no threads are about to start or
339 // exit. It is released again in SafepointSynchronize::end().
340 Threads_lock->lock();
341
342 assert( _state == _not_synchronized, "trying to safepoint synchronize with wrong state");
343
344 int nof_threads = Threads::number_of_threads();
345
346 _nof_threads_hit_polling_page = 0;
347
348 log_debug(safepoint)("Safepoint synchronization initiated using %s wait barrier. (%d threads)", _wait_barrier->description(), nof_threads);
349
350 // Reset the count of active JNI critical threads
351 _current_jni_active_count = 0;
352
353 // Set number of threads to wait for
354 _waiting_to_block = nof_threads;
355
356 jlong safepoint_limit_time = 0;
357 if (SafepointTimeout) {
358 // Set the limit time, so that it can be compared to see if this has taken
359 // too long to complete.
360 safepoint_limit_time = SafepointTracing::start_of_safepoint() + (jlong)(SafepointTimeoutDelay * NANOSECS_PER_MILLISEC);
361 timeout_error_printed = false;
362 }
363
364 EventSafepointStateSynchronization sync_event;
365 int initial_running = 0;
366
367 // Arms the safepoint, _current_jni_active_count and _waiting_to_block must be set before.
368 arm_safepoint();
369
370 // Will spin until all threads are safe.
371 int iterations = synchronize_threads(safepoint_limit_time, nof_threads, &initial_running);
372 assert(_waiting_to_block == 0, "No thread should be running");
373
374 #ifndef PRODUCT
375 // Mark all threads
376 if (VerifyCrossModifyFence) {
377 JavaThreadIteratorWithHandle jtiwh;
378 for (; JavaThread *cur = jtiwh.next(); ) {
379 cur->set_requires_cross_modify_fence(true);
380 }
381 }
382
383 if (safepoint_limit_time != 0) {
384 jlong current_time = os::javaTimeNanos();
385 if (safepoint_limit_time < current_time) {
386 log_warning(safepoint)("# SafepointSynchronize: Finished after "
387 INT64_FORMAT_W(6) " ms",
388 (int64_t)(current_time - SafepointTracing::start_of_safepoint()) / (NANOUNITS / MILLIUNITS));
389 }
390 }
391 #endif
392
393 assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
394
395 // Record state
396 _state = _synchronized;
397
398 OrderAccess::fence();
399
400 // Set the new id
401 ++_safepoint_id;
402
403 #ifdef ASSERT
404 // Make sure all the threads were visited.
405 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur = jtiwh.next(); ) {
406 assert(cur->was_visited_for_critical_count(_safepoint_counter), "missed a thread");
407 }
408 #endif // ASSERT
409
410 post_safepoint_synchronize_event(sync_event,
411 _safepoint_id,
412 initial_running,
413 _waiting_to_block, iterations);
414
415 SafepointTracing::synchronized(nof_threads, initial_running, _nof_threads_hit_polling_page);
416
417 post_safepoint_begin_event(begin_event, _safepoint_id, nof_threads, _current_jni_active_count);
418 }
419
420 void SafepointSynchronize::disarm_safepoint() {
421 uint64_t active_safepoint_counter = _safepoint_counter;
422 {
423 JavaThreadIteratorWithHandle jtiwh;
424 #ifdef ASSERT
425 // A pending_exception cannot be installed during a safepoint. The threads
426 // may install an async exception after they come back from a safepoint into
427 // pending_exception after they unblock. But that should happen later.
428 for (; JavaThread *cur = jtiwh.next(); ) {
429 assert (!(cur->has_pending_exception() &&
430 cur->safepoint_state()->is_at_poll_safepoint()),
431 "safepoint installed a pending exception");
432 }
433 #endif // ASSERT
434
435 OrderAccess::fence(); // keep read and write of _state from floating up
436 assert(_state == _synchronized, "must be synchronized before ending safepoint synchronization");
437
438 // Change state first to _not_synchronized.
439 // No threads should see _synchronized when running.
440 _state = _not_synchronized;
441
442 // Set the next dormant (even) safepoint id.
443 assert((_safepoint_counter & 0x1) == 1, "must be odd");
444 AtomicAccess::release_store(&_safepoint_counter, _safepoint_counter + 1);
445
446 OrderAccess::fence(); // Keep the local state from floating up.
447
448 jtiwh.rewind();
449 for (; JavaThread *current = jtiwh.next(); ) {
450 // Clear the visited flag to ensure that the critical counts are collected properly.
451 DEBUG_ONLY(current->reset_visited_for_critical_count(active_safepoint_counter);)
452 ThreadSafepointState* cur_state = current->safepoint_state();
453 assert(!cur_state->is_running(), "Thread not suspended at safepoint");
454 cur_state->restart(); // TSS _running
455 assert(cur_state->is_running(), "safepoint state has not been reset");
456 }
457 } // ~JavaThreadIteratorWithHandle
458
459 // Release threads lock, so threads can be created/destroyed again.
460 Threads_lock->unlock();
461
462 // Wake threads after local state is correctly set.
463 _wait_barrier->disarm();
464 }
465
466 // Wake up all threads, so they are ready to resume execution after the safepoint
467 // operation has been carried out
468 void SafepointSynchronize::end() {
469 assert(Threads_lock->owned_by_self(), "must hold Threads_lock");
470 SafepointTracing::leave();
471
472 EventSafepointEnd event;
473 assert(Thread::current()->is_VM_thread(), "Only VM thread can execute a safepoint");
474
475 disarm_safepoint();
476
477 Universe::heap()->safepoint_synchronize_end();
478
479 SafepointTracing::end();
480
481 post_safepoint_end_event(event, safepoint_id());
482 }
483
484 // Methods for determining if a JavaThread is safepoint safe.
485
486 // False means unsafe with undetermined state.
487 // True means a determined state, but it may be an unsafe state.
488 // If called from a non-safepoint context safepoint_count MUST be InactiveSafepointCounter.
489 bool SafepointSynchronize::try_stable_load_state(JavaThreadState *state, JavaThread *thread, uint64_t safepoint_count) {
490 assert((safepoint_count != InactiveSafepointCounter &&
491 Thread::current() == (Thread*)VMThread::vm_thread() &&
492 SafepointSynchronize::_state != _not_synchronized)
493 || safepoint_count == InactiveSafepointCounter, "Invalid check");
494
495 // To handle the thread_blocked state on the backedge of the WaitBarrier from
496 // previous safepoint and reading the reset value (0/InactiveSafepointCounter) we
497 // re-read state after we read thread safepoint id. The JavaThread changes its
498 // thread state from thread_blocked before resetting safepoint id to 0.
499 // This guarantees the second read will be from an updated thread state. It can
500 // either be different state making this an unsafe state or it can see blocked
501 // again. When we see blocked twice with a 0 safepoint id, either:
502 // - It is normally blocked, e.g. on Mutex, TBIVM.
503 // - It was in SS:block(), looped around to SS:block() and is blocked on the WaitBarrier.
504 // - It was in SS:block() but now on a Mutex.
505 // All of these cases are safe.
506
507 *state = thread->thread_state();
508 OrderAccess::loadload();
509 uint64_t sid = thread->safepoint_state()->get_safepoint_id(); // Load acquire
510 if (sid != InactiveSafepointCounter && sid != safepoint_count) {
511 // In an old safepoint, state not relevant.
512 return false;
513 }
514 return *state == thread->thread_state();
515 }
516
517 static bool safepoint_safe_with(JavaThread *thread, JavaThreadState state) {
518 switch(state) {
519 case _thread_in_native:
520 // native threads are safe if they have no java stack or have walkable stack
521 return !thread->has_last_Java_frame() || thread->frame_anchor()->walkable();
522
523 case _thread_blocked:
524 // On wait_barrier or blocked.
525 // Blocked threads should already have walkable stack.
526 assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "blocked and not walkable");
527 return true;
528
529 default:
530 return false;
531 }
532 }
533
534 bool SafepointSynchronize::handshake_safe(JavaThread *thread) {
535 if (thread->is_terminated()) {
536 return true;
537 }
538 JavaThreadState stable_state;
539 if (try_stable_load_state(&stable_state, thread, InactiveSafepointCounter)) {
540 return safepoint_safe_with(thread, stable_state);
541 }
542 return false;
543 }
544
545
546 // -------------------------------------------------------------------------------------------------------
547 // Implementation of Safepoint blocking point
548
549 void SafepointSynchronize::block(JavaThread *thread) {
550 assert(thread != nullptr, "thread must be set");
551
552 // Threads shouldn't block if they are in the middle of printing, but...
553 ttyLocker::break_tty_lock_for_safepoint(os::current_thread_id());
554
555 // Only bail from the block() call if the thread is gone from the
556 // thread list; starting to exit should still block.
557 if (thread->is_terminated()) {
558 // block current thread if we come here from native code when VM is gone
559 thread->block_if_vm_exited();
560
561 // otherwise do nothing
562 return;
563 }
564
565 JavaThreadState state = thread->thread_state();
566 thread->frame_anchor()->make_walkable();
567
568 uint64_t safepoint_id = SafepointSynchronize::safepoint_counter();
569
570 // We have no idea where the VMThread is, it might even be at next safepoint.
571 // So we can miss this poll, but stop at next.
572
573 // Load dependent store, it must not pass loading of safepoint_id.
574 thread->safepoint_state()->set_safepoint_id(safepoint_id); // Release store
575
576 // This part we can skip if we notice we miss or are in a future safepoint.
577 OrderAccess::storestore();
578 // Load in wait barrier should not float up
579 thread->set_thread_state_fence(_thread_blocked);
580
581 _wait_barrier->wait(static_cast<int>(safepoint_id));
582 assert(_state != _synchronized, "Can't be");
583
584 // If barrier is disarmed stop store from floating above loads in barrier.
585 OrderAccess::loadstore();
586 thread->set_thread_state(state);
587
588 // Then we reset the safepoint id to inactive.
589 thread->safepoint_state()->reset_safepoint_id(); // Release store
590
591 OrderAccess::fence();
592
593 guarantee(thread->safepoint_state()->get_safepoint_id() == InactiveSafepointCounter,
594 "The safepoint id should be set only in block path");
595
596 // cross_modify_fence is done by SafepointMechanism::process_if_requested
597 // which is the only caller here.
598 }
599
600 // ------------------------------------------------------------------------------------------------------
601 // Exception handlers
602
603
604 void SafepointSynchronize::handle_polling_page_exception(JavaThread *thread) {
605 assert(thread->thread_state() == _thread_in_Java, "should come from Java code");
606 thread->set_thread_state(_thread_in_vm);
607
608 // Enable WXWrite: the function is called implicitly from java code.
609 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, thread));
610
611 if (log_is_enabled(Info, safepoint, stats)) {
612 AtomicAccess::inc(&_nof_threads_hit_polling_page);
613 }
614
615 ThreadSafepointState* state = thread->safepoint_state();
616
617 state->handle_polling_page_exception();
618
619 thread->set_thread_state(_thread_in_Java);
620 }
621
622
623 void SafepointSynchronize::print_safepoint_timeout() {
624 if (!timeout_error_printed) {
625 timeout_error_printed = true;
626 // Print out the thread info which didn't reach the safepoint for debugging
627 // purposes (useful when there are lots of threads in the debugger).
628 LogTarget(Warning, safepoint) lt;
629 if (lt.is_enabled()) {
630 ResourceMark rm;
631 LogStream ls(lt);
632
633 ls.cr();
634 ls.print_cr("# SafepointSynchronize::begin: Timeout detected:");
635 ls.print_cr("# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint.");
636 ls.print_cr("# SafepointSynchronize::begin: Threads which did not reach the safepoint:");
637 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur_thread = jtiwh.next(); ) {
638 if (cur_thread->safepoint_state()->is_running()) {
639 ls.print("# ");
640 cur_thread->print_on(&ls);
641 ls.cr();
642 }
643 }
644 ls.print_cr("# SafepointSynchronize::begin: (End of list)");
645 }
646 }
647
648 // To debug the long safepoint, specify both AbortVMOnSafepointTimeout &
649 // ShowMessageBoxOnError.
650 if (AbortVMOnSafepointTimeout && (os::elapsedTime() * MILLIUNITS > AbortVMOnSafepointTimeoutDelay)) {
651 // Send the blocking thread a signal to terminate and write an error file.
652 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *cur_thread = jtiwh.next(); ) {
653 if (cur_thread->safepoint_state()->is_running()) {
654 VMError::set_safepoint_timed_out_thread(cur_thread);
655 if (!os::signal_thread(cur_thread, SIGILL, "blocking a safepoint")) {
656 break; // Could not send signal. Report fatal error.
657 }
658 // Give cur_thread a chance to report the error and terminate the VM.
659 os::naked_sleep(3000);
660 }
661 }
662 fatal("Safepoint sync time longer than %.6f ms detected when executing %s.",
663 SafepointTimeoutDelay, VMThread::vm_operation()->name());
664 }
665 }
666
667 // -------------------------------------------------------------------------------------------------------
668 // Implementation of ThreadSafepointState
669
670 ThreadSafepointState::ThreadSafepointState(JavaThread *thread)
671 : _at_poll_safepoint(false), _thread(thread), _safepoint_safe(false),
672 _safepoint_id(SafepointSynchronize::InactiveSafepointCounter), _next(nullptr) {
673 }
674
675 void ThreadSafepointState::create(JavaThread *thread) {
676 ThreadSafepointState *state = new ThreadSafepointState(thread);
677 thread->set_safepoint_state(state);
678 }
679
680 void ThreadSafepointState::destroy(JavaThread *thread) {
681 if (thread->safepoint_state()) {
682 delete(thread->safepoint_state());
683 thread->set_safepoint_state(nullptr);
684 }
685 }
686
687 uint64_t ThreadSafepointState::get_safepoint_id() const {
688 return AtomicAccess::load_acquire(&_safepoint_id);
689 }
690
691 void ThreadSafepointState::reset_safepoint_id() {
692 AtomicAccess::release_store(&_safepoint_id, SafepointSynchronize::InactiveSafepointCounter);
693 }
694
695 void ThreadSafepointState::set_safepoint_id(uint64_t safepoint_id) {
696 AtomicAccess::release_store(&_safepoint_id, safepoint_id);
697 }
698
699 void ThreadSafepointState::examine_state_of_thread(uint64_t safepoint_count) {
700 assert(is_running(), "better be running or just have hit safepoint poll");
701
702 JavaThreadState stable_state;
703 if (!SafepointSynchronize::try_stable_load_state(&stable_state, _thread, safepoint_count)) {
704 // We could not get stable state of the JavaThread.
705 // Consider it running and just return.
706 return;
707 }
708
709 if (safepoint_safe_with(_thread, stable_state)) {
710 account_safe_thread();
711 return;
712 }
713
714 // All other thread states will continue to run until they
715 // transition and self-block in state _blocked
716 // Safepoint polling in compiled code causes the Java threads to do the same.
717 // Note: new threads may require a malloc so they must be allowed to finish
718
719 assert(is_running(), "examine_state_of_thread on non-running thread");
720 return;
721 }
722
723 void ThreadSafepointState::account_safe_thread() {
724 SafepointSynchronize::decrement_waiting_to_block();
725 if (_thread->in_critical()) {
726 // Notice that this thread is in a critical section
727 SafepointSynchronize::increment_jni_active_count();
728 }
729 DEBUG_ONLY(_thread->set_visited_for_critical_count(SafepointSynchronize::safepoint_counter());)
730 assert(!_safepoint_safe, "Must be unsafe before safe");
731 _safepoint_safe = true;
732
733 // The oops in the monitor cache are cleared to prevent stale cache entries
734 // from keeping dead objects alive. Because these oops are always cleared
735 // before safepoint operations they are not visited in JavaThread::oops_do.
736 _thread->om_clear_monitor_cache();
737 }
738
739 void ThreadSafepointState::restart() {
740 assert(_safepoint_safe, "Must be safe before unsafe");
741 _safepoint_safe = false;
742 }
743
744 void ThreadSafepointState::print_on(outputStream *st) const {
745 const char *s = _safepoint_safe ? "_at_safepoint" : "_running";
746
747 st->print_cr("Thread: " INTPTR_FORMAT
748 " [0x%2x] State: %s _at_poll_safepoint %d",
749 p2i(_thread), _thread->osthread()->thread_id(), s, _at_poll_safepoint);
750
751 _thread->print_thread_state_on(st);
752 }
753
754 // ---------------------------------------------------------------------------------------------------------------------
755
756 // Process pending operation.
757 void ThreadSafepointState::handle_polling_page_exception() {
758 JavaThread* self = thread();
759 assert(self == JavaThread::current(), "must be self");
760
761 // Step 1: Find the nmethod from the return address
762 address real_return_addr = self->saved_exception_pc();
763
764 CodeBlob *cb = CodeCache::find_blob(real_return_addr);
765 assert(cb != nullptr && cb->is_nmethod(), "return address should be in nmethod");
766 nmethod* nm = cb->as_nmethod();
767
768 // Find frame of caller
769 frame stub_fr = self->last_frame();
770 CodeBlob* stub_cb = stub_fr.cb();
771 assert(stub_cb->is_safepoint_stub(), "must be a safepoint stub");
772 RegisterMap map(self,
773 RegisterMap::UpdateMap::include,
774 RegisterMap::ProcessFrames::skip,
775 RegisterMap::WalkContinuation::skip);
776 frame caller_fr = stub_fr.sender(&map);
777
778 // Should only be poll_return or poll
779 assert( nm->is_at_poll_or_poll_return(real_return_addr), "should not be at call" );
780
781 // This is a poll immediately before a return. The exception handling code
782 // has already had the effect of causing the return to occur, so the execution
783 // will continue immediately after the call. In addition, the oopmap at the
784 // return point does not mark the return value as an oop (if it is), so
785 // it needs a handle here to be updated.
786 if( nm->is_at_poll_return(real_return_addr) ) {
787 ResourceMark rm;
788 // See if return type is an oop.
789 Method* method = nm->method();
790 bool return_oop = method->is_returning_oop();
791 HandleMark hm(self);
792 GrowableArray<Handle> return_values;
793 InlineKlass* vk = nullptr;
794 if (InlineTypeReturnedAsFields && return_oop) {
795 // Check if an inline type is returned as fields
796 vk = InlineKlass::returned_inline_klass(map, &return_oop, method);
797 if (vk != nullptr) {
798 // We're at a safepoint at the return of a method that returns
799 // multiple values. We must make sure we preserve the oop values
800 // across the safepoint.
801 vk->save_oop_fields(map, return_values);
802 }
803 }
804
805 if (return_oop) {
806 // The oop result has been saved on the stack together with all
807 // the other registers. In order to preserve it over GCs we need
808 // to keep it in a handle.
809 oop result = caller_fr.saved_oop_result(&map);
810 assert(oopDesc::is_oop_or_null(result), "must be oop");
811 return_values.push(Handle(self, result));
812 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
813 }
814
815 // We get here if compiled return polls found a reason to call into the VM.
816 // One condition for that is that the top frame is not yet safe to use.
817 // The following stack watermark barrier poll will catch such situations.
818 StackWatermarkSet::after_unwind(self);
819
820 // Process pending operation
821 SafepointMechanism::process_if_requested_with_exit_check(self, true /* check asyncs */);
822
823 // restore oop result, if any
824 if (return_oop) {
825 assert(vk != nullptr || return_values.length() == 1, "only one return value");
826 caller_fr.set_saved_oop_result(&map, return_values.pop()());
827 }
828 // restore oops in scalarized fields
829 if (vk != nullptr) {
830 vk->restore_oop_results(map, return_values);
831 }
832 }
833
834 // This is a safepoint poll. Verify the return address and block.
835 else {
836
837 // verify the blob built the "return address" correctly
838 assert(real_return_addr == caller_fr.pc(), "must match");
839
840 set_at_poll_safepoint(true);
841 // Process pending operation
842 // We never deliver an async exception at a polling point as the
843 // compiler may not have an exception handler for it (polling at
844 // a return point is ok though). We will check for a pending async
845 // exception below and deoptimize if needed. We also cannot deoptimize
846 // and still install the exception here because live registers needed
847 // during deoptimization are clobbered by the exception path. The
848 // exception will just be delivered once we get into the interpreter.
849 SafepointMechanism::process_if_requested_with_exit_check(self, false /* check asyncs */);
850 set_at_poll_safepoint(false);
851
852 if (self->has_async_exception_condition()) {
853 Deoptimization::deoptimize_frame(self, caller_fr.id());
854 log_info(exceptions)("deferred async exception at compiled safepoint");
855 }
856
857 // If an exception has been installed we must verify that the top frame wasn't deoptimized.
858 if (self->has_pending_exception() ) {
859 RegisterMap map(self,
860 RegisterMap::UpdateMap::include,
861 RegisterMap::ProcessFrames::skip,
862 RegisterMap::WalkContinuation::skip);
863 frame caller_fr = stub_fr.sender(&map);
864 if (caller_fr.is_deoptimized_frame()) {
865 // The exception path will destroy registers that are still
866 // live and will be needed during deoptimization, so if we
867 // have an exception now things are messed up. We only check
868 // at this scope because for a poll return it is ok to deoptimize
869 // while having a pending exception since the call we are returning
870 // from already collides with exception handling registers and
871 // so there is no issue (the exception handling path kills call
872 // result registers but this is ok since the exception kills
873 // the result anyway).
874 fatal("Exception installed and deoptimization is pending");
875 }
876 }
877 }
878 }
879
880
881 // -------------------------------------------------------------------------------------------------------
882 // Implementation of SafepointTracing
883
884 jlong SafepointTracing::_last_safepoint_begin_time_ns = 0;
885 jlong SafepointTracing::_last_safepoint_sync_time_ns = 0;
886 jlong SafepointTracing::_last_safepoint_leave_time_ns = 0;
887 jlong SafepointTracing::_last_safepoint_end_time_ns = 0;
888 jlong SafepointTracing::_last_app_time_ns = 0;
889 int SafepointTracing::_nof_threads = 0;
890 int SafepointTracing::_nof_running = 0;
891 int SafepointTracing::_page_trap = 0;
892 VM_Operation::VMOp_Type SafepointTracing::_current_type;
893 jlong SafepointTracing::_max_sync_time = 0;
894 jlong SafepointTracing::_max_vmop_time = 0;
895 uint64_t SafepointTracing::_op_count[VM_Operation::VMOp_Terminating] = {0};
896
897 void SafepointTracing::init() {
898 // Application start
899 _last_safepoint_end_time_ns = os::javaTimeNanos();
900 }
901
902 // Helper method to print the header.
903 static void print_header(outputStream* st) {
904 // The number of spaces is significant here, and should match the format
905 // specifiers in print_statistics().
906
907 st->print("VM Operation "
908 "[ threads: total initial_running ]"
909 "[ time: sync vmop total ]");
910
911 st->print_cr(" page_trap_count");
912 }
913
914 // This prints a nice table. To get the statistics to not shift due to the logging uptime
915 // decorator, use the option as: -Xlog:safepoint+stats:[outputfile]:none
916 void SafepointTracing::statistics_log() {
917 LogTarget(Info, safepoint, stats) lt;
918 assert (lt.is_enabled(), "should only be called when printing statistics is enabled");
919 LogStream ls(lt);
920
921 static int _cur_stat_index = 0;
922
923 // Print header every 30 entries
924 if ((_cur_stat_index % 30) == 0) {
925 print_header(&ls);
926 _cur_stat_index = 1; // wrap
927 } else {
928 _cur_stat_index++;
929 }
930
931 ls.print("%-28s [ "
932 INT32_FORMAT_W(8) " " INT32_FORMAT_W(8) " "
933 "]",
934 VM_Operation::name(_current_type),
935 _nof_threads,
936 _nof_running);
937 ls.print("[ "
938 INT64_FORMAT_W(10) " " INT64_FORMAT_W(10) " " INT64_FORMAT_W(10) " ]",
939 (int64_t)(_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns),
940 (int64_t)(_last_safepoint_end_time_ns - _last_safepoint_sync_time_ns),
941 (int64_t)(_last_safepoint_end_time_ns - _last_safepoint_begin_time_ns));
942
943 ls.print_cr(INT32_FORMAT_W(16), _page_trap);
944 }
945
946 // This method will be called when VM exits. This tries to summarize the sampling.
947 // Current thread may already be deleted, so don't use ResourceMark.
948 void SafepointTracing::statistics_exit_log() {
949 if (!log_is_enabled(Info, safepoint, stats)) {
950 return;
951 }
952 for (int index = 0; index < VM_Operation::VMOp_Terminating; index++) {
953 if (_op_count[index] != 0) {
954 log_info(safepoint, stats)("%-28s" UINT64_FORMAT_W(10), VM_Operation::name(index),
955 _op_count[index]);
956 }
957 }
958
959 log_info(safepoint, stats)("Maximum sync time " INT64_FORMAT" ns",
960 (int64_t)(_max_sync_time));
961 log_info(safepoint, stats)("Maximum vm operation time (except for Exit VM operation) "
962 INT64_FORMAT " ns",
963 (int64_t)(_max_vmop_time));
964 }
965
966 void SafepointTracing::begin(VM_Operation::VMOp_Type type) {
967 _op_count[type]++;
968 _current_type = type;
969
970 // update the time stamp to begin recording safepoint time
971 _last_safepoint_begin_time_ns = os::javaTimeNanos();
972 _last_safepoint_sync_time_ns = 0;
973
974 _last_app_time_ns = _last_safepoint_begin_time_ns - _last_safepoint_end_time_ns;
975 _last_safepoint_end_time_ns = 0;
976
977 RuntimeService::record_safepoint_begin(_last_app_time_ns);
978 }
979
980 void SafepointTracing::synchronized(int nof_threads, int nof_running, int traps) {
981 _last_safepoint_sync_time_ns = os::javaTimeNanos();
982 _nof_threads = nof_threads;
983 _nof_running = nof_running;
984 _page_trap = traps;
985 RuntimeService::record_safepoint_synchronized(_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns);
986 }
987
988 void SafepointTracing::leave() {
989 _last_safepoint_leave_time_ns = os::javaTimeNanos();
990 }
991
992 void SafepointTracing::end() {
993 _last_safepoint_end_time_ns = os::javaTimeNanos();
994
995 if (_max_sync_time < (_last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns)) {
996 _max_sync_time = _last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns;
997 }
998 if (_max_vmop_time < (_last_safepoint_end_time_ns - _last_safepoint_sync_time_ns)) {
999 _max_vmop_time = _last_safepoint_end_time_ns - _last_safepoint_sync_time_ns;
1000 }
1001 if (log_is_enabled(Info, safepoint, stats)) {
1002 statistics_log();
1003 }
1004
1005 log_info(safepoint)(
1006 "Safepoint \"%s\", "
1007 "Time since last: " JLONG_FORMAT " ns, "
1008 "Reaching safepoint: " JLONG_FORMAT " ns, "
1009 "At safepoint: " JLONG_FORMAT " ns, "
1010 "Leaving safepoint: " JLONG_FORMAT " ns, "
1011 "Total: " JLONG_FORMAT " ns, "
1012 "Threads: %d runnable, %d total",
1013 VM_Operation::name(_current_type),
1014 _last_app_time_ns,
1015 _last_safepoint_sync_time_ns - _last_safepoint_begin_time_ns,
1016 _last_safepoint_leave_time_ns - _last_safepoint_sync_time_ns,
1017 _last_safepoint_end_time_ns - _last_safepoint_leave_time_ns,
1018 _last_safepoint_end_time_ns - _last_safepoint_begin_time_ns,
1019 _nof_running,
1020 _nof_threads
1021 );
1022
1023 RuntimeService::record_safepoint_end(_last_safepoint_end_time_ns - _last_safepoint_sync_time_ns);
1024 }