Wed, 27 Aug 2014 08:19:12 -0400
8046598: Scalable Native memory tracking development
Summary: Enhance scalability of native memory tracking
Reviewed-by: coleenp, ctornqvi, gtriantafill
1 /*
2 * Copyright (c) 1997, 2014, 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/classLoader.hpp"
27 #include "classfile/javaClasses.hpp"
28 #include "classfile/systemDictionary.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "code/scopeDesc.hpp"
31 #include "compiler/compileBroker.hpp"
32 #include "interpreter/interpreter.hpp"
33 #include "interpreter/linkResolver.hpp"
34 #include "interpreter/oopMapCache.hpp"
35 #include "jvmtifiles/jvmtiEnv.hpp"
36 #include "memory/gcLocker.inline.hpp"
37 #include "memory/metaspaceShared.hpp"
38 #include "memory/oopFactory.hpp"
39 #include "memory/universe.inline.hpp"
40 #include "oops/instanceKlass.hpp"
41 #include "oops/objArrayOop.hpp"
42 #include "oops/oop.inline.hpp"
43 #include "oops/symbol.hpp"
44 #include "prims/jvm_misc.hpp"
45 #include "prims/jvmtiExport.hpp"
46 #include "prims/jvmtiThreadState.hpp"
47 #include "prims/privilegedStack.hpp"
48 #include "runtime/arguments.hpp"
49 #include "runtime/biasedLocking.hpp"
50 #include "runtime/deoptimization.hpp"
51 #include "runtime/fprofiler.hpp"
52 #include "runtime/frame.inline.hpp"
53 #include "runtime/init.hpp"
54 #include "runtime/interfaceSupport.hpp"
55 #include "runtime/java.hpp"
56 #include "runtime/javaCalls.hpp"
57 #include "runtime/jniPeriodicChecker.hpp"
58 #include "runtime/memprofiler.hpp"
59 #include "runtime/mutexLocker.hpp"
60 #include "runtime/objectMonitor.hpp"
61 #include "runtime/orderAccess.inline.hpp"
62 #include "runtime/osThread.hpp"
63 #include "runtime/safepoint.hpp"
64 #include "runtime/sharedRuntime.hpp"
65 #include "runtime/statSampler.hpp"
66 #include "runtime/stubRoutines.hpp"
67 #include "runtime/task.hpp"
68 #include "runtime/thread.inline.hpp"
69 #include "runtime/threadCritical.hpp"
70 #include "runtime/threadLocalStorage.hpp"
71 #include "runtime/vframe.hpp"
72 #include "runtime/vframeArray.hpp"
73 #include "runtime/vframe_hp.hpp"
74 #include "runtime/vmThread.hpp"
75 #include "runtime/vm_operations.hpp"
76 #include "services/attachListener.hpp"
77 #include "services/management.hpp"
78 #include "services/memTracker.hpp"
79 #include "services/threadService.hpp"
80 #include "trace/tracing.hpp"
81 #include "trace/traceMacros.hpp"
82 #include "utilities/defaultStream.hpp"
83 #include "utilities/dtrace.hpp"
84 #include "utilities/events.hpp"
85 #include "utilities/preserveException.hpp"
86 #include "utilities/macros.hpp"
87 #ifdef TARGET_OS_FAMILY_linux
88 # include "os_linux.inline.hpp"
89 #endif
90 #ifdef TARGET_OS_FAMILY_solaris
91 # include "os_solaris.inline.hpp"
92 #endif
93 #ifdef TARGET_OS_FAMILY_windows
94 # include "os_windows.inline.hpp"
95 #endif
96 #ifdef TARGET_OS_FAMILY_bsd
97 # include "os_bsd.inline.hpp"
98 #endif
99 #if INCLUDE_ALL_GCS
100 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
101 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
102 #include "gc_implementation/parallelScavenge/pcTasks.hpp"
103 #endif // INCLUDE_ALL_GCS
104 #ifdef COMPILER1
105 #include "c1/c1_Compiler.hpp"
106 #endif
107 #ifdef COMPILER2
108 #include "opto/c2compiler.hpp"
109 #include "opto/idealGraphPrinter.hpp"
110 #endif
111 #if INCLUDE_RTM_OPT
112 #include "runtime/rtmLocking.hpp"
113 #endif
115 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
117 #ifdef DTRACE_ENABLED
119 // Only bother with this argument setup if dtrace is available
121 #ifndef USDT2
122 HS_DTRACE_PROBE_DECL(hotspot, vm__init__begin);
123 HS_DTRACE_PROBE_DECL(hotspot, vm__init__end);
124 HS_DTRACE_PROBE_DECL5(hotspot, thread__start, char*, intptr_t,
125 intptr_t, intptr_t, bool);
126 HS_DTRACE_PROBE_DECL5(hotspot, thread__stop, char*, intptr_t,
127 intptr_t, intptr_t, bool);
129 #define DTRACE_THREAD_PROBE(probe, javathread) \
130 { \
131 ResourceMark rm(this); \
132 int len = 0; \
133 const char* name = (javathread)->get_thread_name(); \
134 len = strlen(name); \
135 HS_DTRACE_PROBE5(hotspot, thread__##probe, \
136 name, len, \
137 java_lang_Thread::thread_id((javathread)->threadObj()), \
138 (javathread)->osthread()->thread_id(), \
139 java_lang_Thread::is_daemon((javathread)->threadObj())); \
140 }
142 #else /* USDT2 */
144 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_PROBE_START
145 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_PROBE_STOP
147 #define DTRACE_THREAD_PROBE(probe, javathread) \
148 { \
149 ResourceMark rm(this); \
150 int len = 0; \
151 const char* name = (javathread)->get_thread_name(); \
152 len = strlen(name); \
153 HOTSPOT_THREAD_PROBE_##probe( /* probe = start, stop */ \
154 (char *) name, len, \
155 java_lang_Thread::thread_id((javathread)->threadObj()), \
156 (uintptr_t) (javathread)->osthread()->thread_id(), \
157 java_lang_Thread::is_daemon((javathread)->threadObj())); \
158 }
160 #endif /* USDT2 */
162 #else // ndef DTRACE_ENABLED
164 #define DTRACE_THREAD_PROBE(probe, javathread)
166 #endif // ndef DTRACE_ENABLED
169 // Class hierarchy
170 // - Thread
171 // - VMThread
172 // - WatcherThread
173 // - ConcurrentMarkSweepThread
174 // - JavaThread
175 // - CompilerThread
177 // ======= Thread ========
178 // Support for forcing alignment of thread objects for biased locking
179 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
180 if (UseBiasedLocking) {
181 const int alignment = markOopDesc::biased_lock_alignment;
182 size_t aligned_size = size + (alignment - sizeof(intptr_t));
183 void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC)
184 : AllocateHeap(aligned_size, flags, CURRENT_PC,
185 AllocFailStrategy::RETURN_NULL);
186 void* aligned_addr = (void*) align_size_up((intptr_t) real_malloc_addr, alignment);
187 assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
188 ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
189 "JavaThread alignment code overflowed allocated storage");
190 if (TraceBiasedLocking) {
191 if (aligned_addr != real_malloc_addr)
192 tty->print_cr("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
193 real_malloc_addr, aligned_addr);
194 }
195 ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
196 return aligned_addr;
197 } else {
198 return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
199 : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
200 }
201 }
203 void Thread::operator delete(void* p) {
204 if (UseBiasedLocking) {
205 void* real_malloc_addr = ((Thread*) p)->_real_malloc_address;
206 FreeHeap(real_malloc_addr, mtThread);
207 } else {
208 FreeHeap(p, mtThread);
209 }
210 }
213 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
214 // JavaThread
217 Thread::Thread() {
218 // stack and get_thread
219 set_stack_base(NULL);
220 set_stack_size(0);
221 set_self_raw_id(0);
222 set_lgrp_id(-1);
224 // allocated data structures
225 set_osthread(NULL);
226 set_resource_area(new (mtThread)ResourceArea());
227 DEBUG_ONLY(_current_resource_mark = NULL;)
228 set_handle_area(new (mtThread) HandleArea(NULL));
229 set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
230 set_active_handles(NULL);
231 set_free_handle_block(NULL);
232 set_last_handle_mark(NULL);
234 // This initial value ==> never claimed.
235 _oops_do_parity = 0;
237 // the handle mark links itself to last_handle_mark
238 new HandleMark(this);
240 // plain initialization
241 debug_only(_owned_locks = NULL;)
242 debug_only(_allow_allocation_count = 0;)
243 NOT_PRODUCT(_allow_safepoint_count = 0;)
244 NOT_PRODUCT(_skip_gcalot = false;)
245 _jvmti_env_iteration_count = 0;
246 set_allocated_bytes(0);
247 _vm_operation_started_count = 0;
248 _vm_operation_completed_count = 0;
249 _current_pending_monitor = NULL;
250 _current_pending_monitor_is_from_java = true;
251 _current_waiting_monitor = NULL;
252 _num_nested_signal = 0;
253 omFreeList = NULL ;
254 omFreeCount = 0 ;
255 omFreeProvision = 32 ;
256 omInUseList = NULL ;
257 omInUseCount = 0 ;
259 #ifdef ASSERT
260 _visited_for_critical_count = false;
261 #endif
263 _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true);
264 _suspend_flags = 0;
266 // thread-specific hashCode stream generator state - Marsaglia shift-xor form
267 _hashStateX = os::random() ;
268 _hashStateY = 842502087 ;
269 _hashStateZ = 0x8767 ; // (int)(3579807591LL & 0xffff) ;
270 _hashStateW = 273326509 ;
272 _OnTrap = 0 ;
273 _schedctl = NULL ;
274 _Stalled = 0 ;
275 _TypeTag = 0x2BAD ;
277 // Many of the following fields are effectively final - immutable
278 // Note that nascent threads can't use the Native Monitor-Mutex
279 // construct until the _MutexEvent is initialized ...
280 // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
281 // we might instead use a stack of ParkEvents that we could provision on-demand.
282 // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
283 // and ::Release()
284 _ParkEvent = ParkEvent::Allocate (this) ;
285 _SleepEvent = ParkEvent::Allocate (this) ;
286 _MutexEvent = ParkEvent::Allocate (this) ;
287 _MuxEvent = ParkEvent::Allocate (this) ;
289 #ifdef CHECK_UNHANDLED_OOPS
290 if (CheckUnhandledOops) {
291 _unhandled_oops = new UnhandledOops(this);
292 }
293 #endif // CHECK_UNHANDLED_OOPS
294 #ifdef ASSERT
295 if (UseBiasedLocking) {
296 assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
297 assert(this == _real_malloc_address ||
298 this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
299 "bug in forced alignment of thread objects");
300 }
301 #endif /* ASSERT */
302 }
304 void Thread::initialize_thread_local_storage() {
305 // Note: Make sure this method only calls
306 // non-blocking operations. Otherwise, it might not work
307 // with the thread-startup/safepoint interaction.
309 // During Java thread startup, safepoint code should allow this
310 // method to complete because it may need to allocate memory to
311 // store information for the new thread.
313 // initialize structure dependent on thread local storage
314 ThreadLocalStorage::set_thread(this);
315 }
317 void Thread::record_stack_base_and_size() {
318 set_stack_base(os::current_stack_base());
319 set_stack_size(os::current_stack_size());
320 if (is_Java_thread()) {
321 ((JavaThread*) this)->set_stack_overflow_limit();
322 }
323 // CR 7190089: on Solaris, primordial thread's stack is adjusted
324 // in initialize_thread(). Without the adjustment, stack size is
325 // incorrect if stack is set to unlimited (ulimit -s unlimited).
326 // So far, only Solaris has real implementation of initialize_thread().
327 //
328 // set up any platform-specific state.
329 os::initialize_thread(this);
331 #if INCLUDE_NMT
332 // record thread's native stack, stack grows downward
333 address stack_low_addr = stack_base() - stack_size();
334 MemTracker::record_thread_stack(stack_low_addr, stack_size());
335 #endif // INCLUDE_NMT
336 }
339 Thread::~Thread() {
340 // Reclaim the objectmonitors from the omFreeList of the moribund thread.
341 ObjectSynchronizer::omFlush (this) ;
343 EVENT_THREAD_DESTRUCT(this);
345 // stack_base can be NULL if the thread is never started or exited before
346 // record_stack_base_and_size called. Although, we would like to ensure
347 // that all started threads do call record_stack_base_and_size(), there is
348 // not proper way to enforce that.
349 #if INCLUDE_NMT
350 if (_stack_base != NULL) {
351 address low_stack_addr = stack_base() - stack_size();
352 MemTracker::release_thread_stack(low_stack_addr, stack_size());
353 #ifdef ASSERT
354 set_stack_base(NULL);
355 #endif
356 }
357 #endif // INCLUDE_NMT
359 // deallocate data structures
360 delete resource_area();
361 // since the handle marks are using the handle area, we have to deallocated the root
362 // handle mark before deallocating the thread's handle area,
363 assert(last_handle_mark() != NULL, "check we have an element");
364 delete last_handle_mark();
365 assert(last_handle_mark() == NULL, "check we have reached the end");
367 // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
368 // We NULL out the fields for good hygiene.
369 ParkEvent::Release (_ParkEvent) ; _ParkEvent = NULL ;
370 ParkEvent::Release (_SleepEvent) ; _SleepEvent = NULL ;
371 ParkEvent::Release (_MutexEvent) ; _MutexEvent = NULL ;
372 ParkEvent::Release (_MuxEvent) ; _MuxEvent = NULL ;
374 delete handle_area();
375 delete metadata_handles();
377 // osthread() can be NULL, if creation of thread failed.
378 if (osthread() != NULL) os::free_thread(osthread());
380 delete _SR_lock;
382 // clear thread local storage if the Thread is deleting itself
383 if (this == Thread::current()) {
384 ThreadLocalStorage::set_thread(NULL);
385 } else {
386 // In the case where we're not the current thread, invalidate all the
387 // caches in case some code tries to get the current thread or the
388 // thread that was destroyed, and gets stale information.
389 ThreadLocalStorage::invalidate_all();
390 }
391 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
392 }
394 // NOTE: dummy function for assertion purpose.
395 void Thread::run() {
396 ShouldNotReachHere();
397 }
399 #ifdef ASSERT
400 // Private method to check for dangling thread pointer
401 void check_for_dangling_thread_pointer(Thread *thread) {
402 assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
403 "possibility of dangling Thread pointer");
404 }
405 #endif
408 #ifndef PRODUCT
409 // Tracing method for basic thread operations
410 void Thread::trace(const char* msg, const Thread* const thread) {
411 if (!TraceThreadEvents) return;
412 ResourceMark rm;
413 ThreadCritical tc;
414 const char *name = "non-Java thread";
415 int prio = -1;
416 if (thread->is_Java_thread()
417 && !thread->is_Compiler_thread()) {
418 // The Threads_lock must be held to get information about
419 // this thread but may not be in some situations when
420 // tracing thread events.
421 bool release_Threads_lock = false;
422 if (!Threads_lock->owned_by_self()) {
423 Threads_lock->lock();
424 release_Threads_lock = true;
425 }
426 JavaThread* jt = (JavaThread *)thread;
427 name = (char *)jt->get_thread_name();
428 oop thread_oop = jt->threadObj();
429 if (thread_oop != NULL) {
430 prio = java_lang_Thread::priority(thread_oop);
431 }
432 if (release_Threads_lock) {
433 Threads_lock->unlock();
434 }
435 }
436 tty->print_cr("Thread::%s " INTPTR_FORMAT " [%lx] %s (prio: %d)", msg, thread, thread->osthread()->thread_id(), name, prio);
437 }
438 #endif
441 ThreadPriority Thread::get_priority(const Thread* const thread) {
442 trace("get priority", thread);
443 ThreadPriority priority;
444 // Can return an error!
445 (void)os::get_priority(thread, priority);
446 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
447 return priority;
448 }
450 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
451 trace("set priority", thread);
452 debug_only(check_for_dangling_thread_pointer(thread);)
453 // Can return an error!
454 (void)os::set_priority(thread, priority);
455 }
458 void Thread::start(Thread* thread) {
459 trace("start", thread);
460 // Start is different from resume in that its safety is guaranteed by context or
461 // being called from a Java method synchronized on the Thread object.
462 if (!DisableStartThread) {
463 if (thread->is_Java_thread()) {
464 // Initialize the thread state to RUNNABLE before starting this thread.
465 // Can not set it after the thread started because we do not know the
466 // exact thread state at that time. It could be in MONITOR_WAIT or
467 // in SLEEPING or some other state.
468 java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
469 java_lang_Thread::RUNNABLE);
470 }
471 os::start_thread(thread);
472 }
473 }
475 // Enqueue a VM_Operation to do the job for us - sometime later
476 void Thread::send_async_exception(oop java_thread, oop java_throwable) {
477 VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable);
478 VMThread::execute(vm_stop);
479 }
482 //
483 // Check if an external suspend request has completed (or has been
484 // cancelled). Returns true if the thread is externally suspended and
485 // false otherwise.
486 //
487 // The bits parameter returns information about the code path through
488 // the routine. Useful for debugging:
489 //
490 // set in is_ext_suspend_completed():
491 // 0x00000001 - routine was entered
492 // 0x00000010 - routine return false at end
493 // 0x00000100 - thread exited (return false)
494 // 0x00000200 - suspend request cancelled (return false)
495 // 0x00000400 - thread suspended (return true)
496 // 0x00001000 - thread is in a suspend equivalent state (return true)
497 // 0x00002000 - thread is native and walkable (return true)
498 // 0x00004000 - thread is native_trans and walkable (needed retry)
499 //
500 // set in wait_for_ext_suspend_completion():
501 // 0x00010000 - routine was entered
502 // 0x00020000 - suspend request cancelled before loop (return false)
503 // 0x00040000 - thread suspended before loop (return true)
504 // 0x00080000 - suspend request cancelled in loop (return false)
505 // 0x00100000 - thread suspended in loop (return true)
506 // 0x00200000 - suspend not completed during retry loop (return false)
507 //
509 // Helper class for tracing suspend wait debug bits.
510 //
511 // 0x00000100 indicates that the target thread exited before it could
512 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
513 // 0x00080000 each indicate a cancelled suspend request so they don't
514 // count as wait failures either.
515 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000)
517 class TraceSuspendDebugBits : public StackObj {
518 private:
519 JavaThread * jt;
520 bool is_wait;
521 bool called_by_wait; // meaningful when !is_wait
522 uint32_t * bits;
524 public:
525 TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait,
526 uint32_t *_bits) {
527 jt = _jt;
528 is_wait = _is_wait;
529 called_by_wait = _called_by_wait;
530 bits = _bits;
531 }
533 ~TraceSuspendDebugBits() {
534 if (!is_wait) {
535 #if 1
536 // By default, don't trace bits for is_ext_suspend_completed() calls.
537 // That trace is very chatty.
538 return;
539 #else
540 if (!called_by_wait) {
541 // If tracing for is_ext_suspend_completed() is enabled, then only
542 // trace calls to it from wait_for_ext_suspend_completion()
543 return;
544 }
545 #endif
546 }
548 if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) {
549 if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) {
550 MutexLocker ml(Threads_lock); // needed for get_thread_name()
551 ResourceMark rm;
553 tty->print_cr(
554 "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
555 jt->get_thread_name(), *bits);
557 guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed");
558 }
559 }
560 }
561 };
562 #undef DEBUG_FALSE_BITS
565 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits) {
566 TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
568 bool did_trans_retry = false; // only do thread_in_native_trans retry once
569 bool do_trans_retry; // flag to force the retry
571 *bits |= 0x00000001;
573 do {
574 do_trans_retry = false;
576 if (is_exiting()) {
577 // Thread is in the process of exiting. This is always checked
578 // first to reduce the risk of dereferencing a freed JavaThread.
579 *bits |= 0x00000100;
580 return false;
581 }
583 if (!is_external_suspend()) {
584 // Suspend request is cancelled. This is always checked before
585 // is_ext_suspended() to reduce the risk of a rogue resume
586 // confusing the thread that made the suspend request.
587 *bits |= 0x00000200;
588 return false;
589 }
591 if (is_ext_suspended()) {
592 // thread is suspended
593 *bits |= 0x00000400;
594 return true;
595 }
597 // Now that we no longer do hard suspends of threads running
598 // native code, the target thread can be changing thread state
599 // while we are in this routine:
600 //
601 // _thread_in_native -> _thread_in_native_trans -> _thread_blocked
602 //
603 // We save a copy of the thread state as observed at this moment
604 // and make our decision about suspend completeness based on the
605 // copy. This closes the race where the thread state is seen as
606 // _thread_in_native_trans in the if-thread_blocked check, but is
607 // seen as _thread_blocked in if-thread_in_native_trans check.
608 JavaThreadState save_state = thread_state();
610 if (save_state == _thread_blocked && is_suspend_equivalent()) {
611 // If the thread's state is _thread_blocked and this blocking
612 // condition is known to be equivalent to a suspend, then we can
613 // consider the thread to be externally suspended. This means that
614 // the code that sets _thread_blocked has been modified to do
615 // self-suspension if the blocking condition releases. We also
616 // used to check for CONDVAR_WAIT here, but that is now covered by
617 // the _thread_blocked with self-suspension check.
618 //
619 // Return true since we wouldn't be here unless there was still an
620 // external suspend request.
621 *bits |= 0x00001000;
622 return true;
623 } else if (save_state == _thread_in_native && frame_anchor()->walkable()) {
624 // Threads running native code will self-suspend on native==>VM/Java
625 // transitions. If its stack is walkable (should always be the case
626 // unless this function is called before the actual java_suspend()
627 // call), then the wait is done.
628 *bits |= 0x00002000;
629 return true;
630 } else if (!called_by_wait && !did_trans_retry &&
631 save_state == _thread_in_native_trans &&
632 frame_anchor()->walkable()) {
633 // The thread is transitioning from thread_in_native to another
634 // thread state. check_safepoint_and_suspend_for_native_trans()
635 // will force the thread to self-suspend. If it hasn't gotten
636 // there yet we may have caught the thread in-between the native
637 // code check above and the self-suspend. Lucky us. If we were
638 // called by wait_for_ext_suspend_completion(), then it
639 // will be doing the retries so we don't have to.
640 //
641 // Since we use the saved thread state in the if-statement above,
642 // there is a chance that the thread has already transitioned to
643 // _thread_blocked by the time we get here. In that case, we will
644 // make a single unnecessary pass through the logic below. This
645 // doesn't hurt anything since we still do the trans retry.
647 *bits |= 0x00004000;
649 // Once the thread leaves thread_in_native_trans for another
650 // thread state, we break out of this retry loop. We shouldn't
651 // need this flag to prevent us from getting back here, but
652 // sometimes paranoia is good.
653 did_trans_retry = true;
655 // We wait for the thread to transition to a more usable state.
656 for (int i = 1; i <= SuspendRetryCount; i++) {
657 // We used to do an "os::yield_all(i)" call here with the intention
658 // that yielding would increase on each retry. However, the parameter
659 // is ignored on Linux which means the yield didn't scale up. Waiting
660 // on the SR_lock below provides a much more predictable scale up for
661 // the delay. It also provides a simple/direct point to check for any
662 // safepoint requests from the VMThread
664 // temporarily drops SR_lock while doing wait with safepoint check
665 // (if we're a JavaThread - the WatcherThread can also call this)
666 // and increase delay with each retry
667 SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
669 // check the actual thread state instead of what we saved above
670 if (thread_state() != _thread_in_native_trans) {
671 // the thread has transitioned to another thread state so
672 // try all the checks (except this one) one more time.
673 do_trans_retry = true;
674 break;
675 }
676 } // end retry loop
679 }
680 } while (do_trans_retry);
682 *bits |= 0x00000010;
683 return false;
684 }
686 //
687 // Wait for an external suspend request to complete (or be cancelled).
688 // Returns true if the thread is externally suspended and false otherwise.
689 //
690 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
691 uint32_t *bits) {
692 TraceSuspendDebugBits tsdb(this, true /* is_wait */,
693 false /* !called_by_wait */, bits);
695 // local flag copies to minimize SR_lock hold time
696 bool is_suspended;
697 bool pending;
698 uint32_t reset_bits;
700 // set a marker so is_ext_suspend_completed() knows we are the caller
701 *bits |= 0x00010000;
703 // We use reset_bits to reinitialize the bits value at the top of
704 // each retry loop. This allows the caller to make use of any
705 // unused bits for their own marking purposes.
706 reset_bits = *bits;
708 {
709 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
710 is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
711 delay, bits);
712 pending = is_external_suspend();
713 }
714 // must release SR_lock to allow suspension to complete
716 if (!pending) {
717 // A cancelled suspend request is the only false return from
718 // is_ext_suspend_completed() that keeps us from entering the
719 // retry loop.
720 *bits |= 0x00020000;
721 return false;
722 }
724 if (is_suspended) {
725 *bits |= 0x00040000;
726 return true;
727 }
729 for (int i = 1; i <= retries; i++) {
730 *bits = reset_bits; // reinit to only track last retry
732 // We used to do an "os::yield_all(i)" call here with the intention
733 // that yielding would increase on each retry. However, the parameter
734 // is ignored on Linux which means the yield didn't scale up. Waiting
735 // on the SR_lock below provides a much more predictable scale up for
736 // the delay. It also provides a simple/direct point to check for any
737 // safepoint requests from the VMThread
739 {
740 MutexLocker ml(SR_lock());
741 // wait with safepoint check (if we're a JavaThread - the WatcherThread
742 // can also call this) and increase delay with each retry
743 SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
745 is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
746 delay, bits);
748 // It is possible for the external suspend request to be cancelled
749 // (by a resume) before the actual suspend operation is completed.
750 // Refresh our local copy to see if we still need to wait.
751 pending = is_external_suspend();
752 }
754 if (!pending) {
755 // A cancelled suspend request is the only false return from
756 // is_ext_suspend_completed() that keeps us from staying in the
757 // retry loop.
758 *bits |= 0x00080000;
759 return false;
760 }
762 if (is_suspended) {
763 *bits |= 0x00100000;
764 return true;
765 }
766 } // end retry loop
768 // thread did not suspend after all our retries
769 *bits |= 0x00200000;
770 return false;
771 }
773 #ifndef PRODUCT
774 void JavaThread::record_jump(address target, address instr, const char* file, int line) {
776 // This should not need to be atomic as the only way for simultaneous
777 // updates is via interrupts. Even then this should be rare or non-existant
778 // and we don't care that much anyway.
780 int index = _jmp_ring_index;
781 _jmp_ring_index = (index + 1 ) & (jump_ring_buffer_size - 1);
782 _jmp_ring[index]._target = (intptr_t) target;
783 _jmp_ring[index]._instruction = (intptr_t) instr;
784 _jmp_ring[index]._file = file;
785 _jmp_ring[index]._line = line;
786 }
787 #endif /* PRODUCT */
789 // Called by flat profiler
790 // Callers have already called wait_for_ext_suspend_completion
791 // The assertion for that is currently too complex to put here:
792 bool JavaThread::profile_last_Java_frame(frame* _fr) {
793 bool gotframe = false;
794 // self suspension saves needed state.
795 if (has_last_Java_frame() && _anchor.walkable()) {
796 *_fr = pd_last_frame();
797 gotframe = true;
798 }
799 return gotframe;
800 }
802 void Thread::interrupt(Thread* thread) {
803 trace("interrupt", thread);
804 debug_only(check_for_dangling_thread_pointer(thread);)
805 os::interrupt(thread);
806 }
808 bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) {
809 trace("is_interrupted", thread);
810 debug_only(check_for_dangling_thread_pointer(thread);)
811 // Note: If clear_interrupted==false, this simply fetches and
812 // returns the value of the field osthread()->interrupted().
813 return os::is_interrupted(thread, clear_interrupted);
814 }
817 // GC Support
818 bool Thread::claim_oops_do_par_case(int strong_roots_parity) {
819 jint thread_parity = _oops_do_parity;
820 if (thread_parity != strong_roots_parity) {
821 jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity);
822 if (res == thread_parity) {
823 return true;
824 } else {
825 guarantee(res == strong_roots_parity, "Or else what?");
826 assert(SharedHeap::heap()->workers()->active_workers() > 0,
827 "Should only fail when parallel.");
828 return false;
829 }
830 }
831 assert(SharedHeap::heap()->workers()->active_workers() > 0,
832 "Should only fail when parallel.");
833 return false;
834 }
836 void Thread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
837 active_handles()->oops_do(f);
838 // Do oop for ThreadShadow
839 f->do_oop((oop*)&_pending_exception);
840 handle_area()->oops_do(f);
841 }
843 void Thread::nmethods_do(CodeBlobClosure* cf) {
844 // no nmethods in a generic thread...
845 }
847 void Thread::metadata_do(void f(Metadata*)) {
848 if (metadata_handles() != NULL) {
849 for (int i = 0; i< metadata_handles()->length(); i++) {
850 f(metadata_handles()->at(i));
851 }
852 }
853 }
855 void Thread::print_on(outputStream* st) const {
856 // get_priority assumes osthread initialized
857 if (osthread() != NULL) {
858 int os_prio;
859 if (os::get_native_priority(this, &os_prio) == OS_OK) {
860 st->print("os_prio=%d ", os_prio);
861 }
862 st->print("tid=" INTPTR_FORMAT " ", this);
863 osthread()->print_on(st);
864 }
865 debug_only(if (WizardMode) print_owned_locks_on(st);)
866 }
868 // Thread::print_on_error() is called by fatal error handler. Don't use
869 // any lock or allocate memory.
870 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
871 if (is_VM_thread()) st->print("VMThread");
872 else if (is_Compiler_thread()) st->print("CompilerThread");
873 else if (is_Java_thread()) st->print("JavaThread");
874 else if (is_GC_task_thread()) st->print("GCTaskThread");
875 else if (is_Watcher_thread()) st->print("WatcherThread");
876 else if (is_ConcurrentGC_thread()) st->print("ConcurrentGCThread");
877 else st->print("Thread");
879 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
880 _stack_base - _stack_size, _stack_base);
882 if (osthread()) {
883 st->print(" [id=%d]", osthread()->thread_id());
884 }
885 }
887 #ifdef ASSERT
888 void Thread::print_owned_locks_on(outputStream* st) const {
889 Monitor *cur = _owned_locks;
890 if (cur == NULL) {
891 st->print(" (no locks) ");
892 } else {
893 st->print_cr(" Locks owned:");
894 while(cur) {
895 cur->print_on(st);
896 cur = cur->next();
897 }
898 }
899 }
901 static int ref_use_count = 0;
903 bool Thread::owns_locks_but_compiled_lock() const {
904 for(Monitor *cur = _owned_locks; cur; cur = cur->next()) {
905 if (cur != Compile_lock) return true;
906 }
907 return false;
908 }
911 #endif
913 #ifndef PRODUCT
915 // The flag: potential_vm_operation notifies if this particular safepoint state could potential
916 // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that
917 // no threads which allow_vm_block's are held
918 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
919 // Check if current thread is allowed to block at a safepoint
920 if (!(_allow_safepoint_count == 0))
921 fatal("Possible safepoint reached by thread that does not allow it");
922 if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
923 fatal("LEAF method calling lock?");
924 }
926 #ifdef ASSERT
927 if (potential_vm_operation && is_Java_thread()
928 && !Universe::is_bootstrapping()) {
929 // Make sure we do not hold any locks that the VM thread also uses.
930 // This could potentially lead to deadlocks
931 for(Monitor *cur = _owned_locks; cur; cur = cur->next()) {
932 // Threads_lock is special, since the safepoint synchronization will not start before this is
933 // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock,
934 // since it is used to transfer control between JavaThreads and the VMThread
935 // Do not *exclude* any locks unless you are absolutly sure it is correct. Ask someone else first!
936 if ( (cur->allow_vm_block() &&
937 cur != Threads_lock &&
938 cur != Compile_lock && // Temporary: should not be necessary when we get spearate compilation
939 cur != VMOperationRequest_lock &&
940 cur != VMOperationQueue_lock) ||
941 cur->rank() == Mutex::special) {
942 warning("Thread holding lock at safepoint that vm can block on: %s", cur->name());
943 }
944 }
945 }
947 if (GCALotAtAllSafepoints) {
948 // We could enter a safepoint here and thus have a gc
949 InterfaceSupport::check_gc_alot();
950 }
951 #endif
952 }
953 #endif
955 bool Thread::is_in_stack(address adr) const {
956 assert(Thread::current() == this, "is_in_stack can only be called from current thread");
957 address end = os::current_stack_pointer();
958 // Allow non Java threads to call this without stack_base
959 if (_stack_base == NULL) return true;
960 if (stack_base() >= adr && adr >= end) return true;
962 return false;
963 }
966 bool Thread::is_in_usable_stack(address adr) const {
967 size_t stack_guard_size = os::uses_stack_guard_pages() ? (StackYellowPages + StackRedPages) * os::vm_page_size() : 0;
968 size_t usable_stack_size = _stack_size - stack_guard_size;
970 return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size));
971 }
974 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
975 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
976 // used for compilation in the future. If that change is made, the need for these methods
977 // should be revisited, and they should be removed if possible.
979 bool Thread::is_lock_owned(address adr) const {
980 return on_local_stack(adr);
981 }
983 bool Thread::set_as_starting_thread() {
984 // NOTE: this must be called inside the main thread.
985 return os::create_main_thread((JavaThread*)this);
986 }
988 static void initialize_class(Symbol* class_name, TRAPS) {
989 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
990 InstanceKlass::cast(klass)->initialize(CHECK);
991 }
994 // Creates the initial ThreadGroup
995 static Handle create_initial_thread_group(TRAPS) {
996 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ThreadGroup(), true, CHECK_NH);
997 instanceKlassHandle klass (THREAD, k);
999 Handle system_instance = klass->allocate_instance_handle(CHECK_NH);
1000 {
1001 JavaValue result(T_VOID);
1002 JavaCalls::call_special(&result,
1003 system_instance,
1004 klass,
1005 vmSymbols::object_initializer_name(),
1006 vmSymbols::void_method_signature(),
1007 CHECK_NH);
1008 }
1009 Universe::set_system_thread_group(system_instance());
1011 Handle main_instance = klass->allocate_instance_handle(CHECK_NH);
1012 {
1013 JavaValue result(T_VOID);
1014 Handle string = java_lang_String::create_from_str("main", CHECK_NH);
1015 JavaCalls::call_special(&result,
1016 main_instance,
1017 klass,
1018 vmSymbols::object_initializer_name(),
1019 vmSymbols::threadgroup_string_void_signature(),
1020 system_instance,
1021 string,
1022 CHECK_NH);
1023 }
1024 return main_instance;
1025 }
1027 // Creates the initial Thread
1028 static oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) {
1029 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_NULL);
1030 instanceKlassHandle klass (THREAD, k);
1031 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL);
1033 java_lang_Thread::set_thread(thread_oop(), thread);
1034 java_lang_Thread::set_priority(thread_oop(), NormPriority);
1035 thread->set_threadObj(thread_oop());
1037 Handle string = java_lang_String::create_from_str("main", CHECK_NULL);
1039 JavaValue result(T_VOID);
1040 JavaCalls::call_special(&result, thread_oop,
1041 klass,
1042 vmSymbols::object_initializer_name(),
1043 vmSymbols::threadgroup_string_void_signature(),
1044 thread_group,
1045 string,
1046 CHECK_NULL);
1047 return thread_oop();
1048 }
1050 static void call_initializeSystemClass(TRAPS) {
1051 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
1052 instanceKlassHandle klass (THREAD, k);
1054 JavaValue result(T_VOID);
1055 JavaCalls::call_static(&result, klass, vmSymbols::initializeSystemClass_name(),
1056 vmSymbols::void_method_signature(), CHECK);
1057 }
1059 char java_runtime_name[128] = "";
1060 char java_runtime_version[128] = "";
1062 // extract the JRE name from sun.misc.Version.java_runtime_name
1063 static const char* get_java_runtime_name(TRAPS) {
1064 Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(),
1065 Handle(), Handle(), CHECK_AND_CLEAR_NULL);
1066 fieldDescriptor fd;
1067 bool found = k != NULL &&
1068 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(),
1069 vmSymbols::string_signature(), &fd);
1070 if (found) {
1071 oop name_oop = k->java_mirror()->obj_field(fd.offset());
1072 if (name_oop == NULL)
1073 return NULL;
1074 const char* name = java_lang_String::as_utf8_string(name_oop,
1075 java_runtime_name,
1076 sizeof(java_runtime_name));
1077 return name;
1078 } else {
1079 return NULL;
1080 }
1081 }
1083 // extract the JRE version from sun.misc.Version.java_runtime_version
1084 static const char* get_java_runtime_version(TRAPS) {
1085 Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(),
1086 Handle(), Handle(), CHECK_AND_CLEAR_NULL);
1087 fieldDescriptor fd;
1088 bool found = k != NULL &&
1089 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(),
1090 vmSymbols::string_signature(), &fd);
1091 if (found) {
1092 oop name_oop = k->java_mirror()->obj_field(fd.offset());
1093 if (name_oop == NULL)
1094 return NULL;
1095 const char* name = java_lang_String::as_utf8_string(name_oop,
1096 java_runtime_version,
1097 sizeof(java_runtime_version));
1098 return name;
1099 } else {
1100 return NULL;
1101 }
1102 }
1104 // General purpose hook into Java code, run once when the VM is initialized.
1105 // The Java library method itself may be changed independently from the VM.
1106 static void call_postVMInitHook(TRAPS) {
1107 Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_PostVMInitHook(), THREAD);
1108 instanceKlassHandle klass (THREAD, k);
1109 if (klass.not_null()) {
1110 JavaValue result(T_VOID);
1111 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
1112 vmSymbols::void_method_signature(),
1113 CHECK);
1114 }
1115 }
1117 static void reset_vm_info_property(TRAPS) {
1118 // the vm info string
1119 ResourceMark rm(THREAD);
1120 const char *vm_info = VM_Version::vm_info_string();
1122 // java.lang.System class
1123 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
1124 instanceKlassHandle klass (THREAD, k);
1126 // setProperty arguments
1127 Handle key_str = java_lang_String::create_from_str("java.vm.info", CHECK);
1128 Handle value_str = java_lang_String::create_from_str(vm_info, CHECK);
1130 // return value
1131 JavaValue r(T_OBJECT);
1133 // public static String setProperty(String key, String value);
1134 JavaCalls::call_static(&r,
1135 klass,
1136 vmSymbols::setProperty_name(),
1137 vmSymbols::string_string_string_signature(),
1138 key_str,
1139 value_str,
1140 CHECK);
1141 }
1144 void JavaThread::allocate_threadObj(Handle thread_group, char* thread_name, bool daemon, TRAPS) {
1145 assert(thread_group.not_null(), "thread group should be specified");
1146 assert(threadObj() == NULL, "should only create Java thread object once");
1148 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
1149 instanceKlassHandle klass (THREAD, k);
1150 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
1152 java_lang_Thread::set_thread(thread_oop(), this);
1153 java_lang_Thread::set_priority(thread_oop(), NormPriority);
1154 set_threadObj(thread_oop());
1156 JavaValue result(T_VOID);
1157 if (thread_name != NULL) {
1158 Handle name = java_lang_String::create_from_str(thread_name, CHECK);
1159 // Thread gets assigned specified name and null target
1160 JavaCalls::call_special(&result,
1161 thread_oop,
1162 klass,
1163 vmSymbols::object_initializer_name(),
1164 vmSymbols::threadgroup_string_void_signature(),
1165 thread_group, // Argument 1
1166 name, // Argument 2
1167 THREAD);
1168 } else {
1169 // Thread gets assigned name "Thread-nnn" and null target
1170 // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
1171 JavaCalls::call_special(&result,
1172 thread_oop,
1173 klass,
1174 vmSymbols::object_initializer_name(),
1175 vmSymbols::threadgroup_runnable_void_signature(),
1176 thread_group, // Argument 1
1177 Handle(), // Argument 2
1178 THREAD);
1179 }
1182 if (daemon) {
1183 java_lang_Thread::set_daemon(thread_oop());
1184 }
1186 if (HAS_PENDING_EXCEPTION) {
1187 return;
1188 }
1190 KlassHandle group(this, SystemDictionary::ThreadGroup_klass());
1191 Handle threadObj(this, this->threadObj());
1193 JavaCalls::call_special(&result,
1194 thread_group,
1195 group,
1196 vmSymbols::add_method_name(),
1197 vmSymbols::thread_void_signature(),
1198 threadObj, // Arg 1
1199 THREAD);
1202 }
1204 // NamedThread -- non-JavaThread subclasses with multiple
1205 // uniquely named instances should derive from this.
1206 NamedThread::NamedThread() : Thread() {
1207 _name = NULL;
1208 _processed_thread = NULL;
1209 }
1211 NamedThread::~NamedThread() {
1212 if (_name != NULL) {
1213 FREE_C_HEAP_ARRAY(char, _name, mtThread);
1214 _name = NULL;
1215 }
1216 }
1218 void NamedThread::set_name(const char* format, ...) {
1219 guarantee(_name == NULL, "Only get to set name once.");
1220 _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
1221 guarantee(_name != NULL, "alloc failure");
1222 va_list ap;
1223 va_start(ap, format);
1224 jio_vsnprintf(_name, max_name_len, format, ap);
1225 va_end(ap);
1226 }
1228 // ======= WatcherThread ========
1230 // The watcher thread exists to simulate timer interrupts. It should
1231 // be replaced by an abstraction over whatever native support for
1232 // timer interrupts exists on the platform.
1234 WatcherThread* WatcherThread::_watcher_thread = NULL;
1235 bool WatcherThread::_startable = false;
1236 volatile bool WatcherThread::_should_terminate = false;
1238 WatcherThread::WatcherThread() : Thread(), _crash_protection(NULL) {
1239 assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
1240 if (os::create_thread(this, os::watcher_thread)) {
1241 _watcher_thread = this;
1243 // Set the watcher thread to the highest OS priority which should not be
1244 // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY
1245 // is created. The only normal thread using this priority is the reference
1246 // handler thread, which runs for very short intervals only.
1247 // If the VMThread's priority is not lower than the WatcherThread profiling
1248 // will be inaccurate.
1249 os::set_priority(this, MaxPriority);
1250 if (!DisableStartThread) {
1251 os::start_thread(this);
1252 }
1253 }
1254 }
1256 int WatcherThread::sleep() const {
1257 MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
1259 // remaining will be zero if there are no tasks,
1260 // causing the WatcherThread to sleep until a task is
1261 // enrolled
1262 int remaining = PeriodicTask::time_to_wait();
1263 int time_slept = 0;
1265 // we expect this to timeout - we only ever get unparked when
1266 // we should terminate or when a new task has been enrolled
1267 OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
1269 jlong time_before_loop = os::javaTimeNanos();
1271 for (;;) {
1272 bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag, remaining);
1273 jlong now = os::javaTimeNanos();
1275 if (remaining == 0) {
1276 // if we didn't have any tasks we could have waited for a long time
1277 // consider the time_slept zero and reset time_before_loop
1278 time_slept = 0;
1279 time_before_loop = now;
1280 } else {
1281 // need to recalulate since we might have new tasks in _tasks
1282 time_slept = (int) ((now - time_before_loop) / 1000000);
1283 }
1285 // Change to task list or spurious wakeup of some kind
1286 if (timedout || _should_terminate) {
1287 break;
1288 }
1290 remaining = PeriodicTask::time_to_wait();
1291 if (remaining == 0) {
1292 // Last task was just disenrolled so loop around and wait until
1293 // another task gets enrolled
1294 continue;
1295 }
1297 remaining -= time_slept;
1298 if (remaining <= 0)
1299 break;
1300 }
1302 return time_slept;
1303 }
1305 void WatcherThread::run() {
1306 assert(this == watcher_thread(), "just checking");
1308 this->record_stack_base_and_size();
1309 this->initialize_thread_local_storage();
1310 this->set_active_handles(JNIHandleBlock::allocate_block());
1311 while(!_should_terminate) {
1312 assert(watcher_thread() == Thread::current(), "thread consistency check");
1313 assert(watcher_thread() == this, "thread consistency check");
1315 // Calculate how long it'll be until the next PeriodicTask work
1316 // should be done, and sleep that amount of time.
1317 int time_waited = sleep();
1319 if (is_error_reported()) {
1320 // A fatal error has happened, the error handler(VMError::report_and_die)
1321 // should abort JVM after creating an error log file. However in some
1322 // rare cases, the error handler itself might deadlock. Here we try to
1323 // kill JVM if the fatal error handler fails to abort in 2 minutes.
1324 //
1325 // This code is in WatcherThread because WatcherThread wakes up
1326 // periodically so the fatal error handler doesn't need to do anything;
1327 // also because the WatcherThread is less likely to crash than other
1328 // threads.
1330 for (;;) {
1331 if (!ShowMessageBoxOnError
1332 && (OnError == NULL || OnError[0] == '\0')
1333 && Arguments::abort_hook() == NULL) {
1334 os::sleep(this, 2 * 60 * 1000, false);
1335 fdStream err(defaultStream::output_fd());
1336 err.print_raw_cr("# [ timer expired, abort... ]");
1337 // skip atexit/vm_exit/vm_abort hooks
1338 os::die();
1339 }
1341 // Wake up 5 seconds later, the fatal handler may reset OnError or
1342 // ShowMessageBoxOnError when it is ready to abort.
1343 os::sleep(this, 5 * 1000, false);
1344 }
1345 }
1347 PeriodicTask::real_time_tick(time_waited);
1348 }
1350 // Signal that it is terminated
1351 {
1352 MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag);
1353 _watcher_thread = NULL;
1354 Terminator_lock->notify();
1355 }
1357 // Thread destructor usually does this..
1358 ThreadLocalStorage::set_thread(NULL);
1359 }
1361 void WatcherThread::start() {
1362 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1364 if (watcher_thread() == NULL && _startable) {
1365 _should_terminate = false;
1366 // Create the single instance of WatcherThread
1367 new WatcherThread();
1368 }
1369 }
1371 void WatcherThread::make_startable() {
1372 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1373 _startable = true;
1374 }
1376 void WatcherThread::stop() {
1377 {
1378 MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
1379 _should_terminate = true;
1380 OrderAccess::fence(); // ensure WatcherThread sees update in main loop
1382 WatcherThread* watcher = watcher_thread();
1383 if (watcher != NULL)
1384 watcher->unpark();
1385 }
1387 // it is ok to take late safepoints here, if needed
1388 MutexLocker mu(Terminator_lock);
1390 while(watcher_thread() != NULL) {
1391 // This wait should make safepoint checks, wait without a timeout,
1392 // and wait as a suspend-equivalent condition.
1393 //
1394 // Note: If the FlatProfiler is running, then this thread is waiting
1395 // for the WatcherThread to terminate and the WatcherThread, via the
1396 // FlatProfiler task, is waiting for the external suspend request on
1397 // this thread to complete. wait_for_ext_suspend_completion() will
1398 // eventually timeout, but that takes time. Making this wait a
1399 // suspend-equivalent condition solves that timeout problem.
1400 //
1401 Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
1402 Mutex::_as_suspend_equivalent_flag);
1403 }
1404 }
1406 void WatcherThread::unpark() {
1407 MutexLockerEx ml(PeriodicTask_lock->owned_by_self() ? NULL : PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
1408 PeriodicTask_lock->notify();
1409 }
1411 void WatcherThread::print_on(outputStream* st) const {
1412 st->print("\"%s\" ", name());
1413 Thread::print_on(st);
1414 st->cr();
1415 }
1417 // ======= JavaThread ========
1419 // A JavaThread is a normal Java thread
1421 void JavaThread::initialize() {
1422 // Initialize fields
1424 // Set the claimed par_id to UINT_MAX (ie not claiming any par_ids)
1425 set_claimed_par_id(UINT_MAX);
1427 set_saved_exception_pc(NULL);
1428 set_threadObj(NULL);
1429 _anchor.clear();
1430 set_entry_point(NULL);
1431 set_jni_functions(jni_functions());
1432 set_callee_target(NULL);
1433 set_vm_result(NULL);
1434 set_vm_result_2(NULL);
1435 set_vframe_array_head(NULL);
1436 set_vframe_array_last(NULL);
1437 set_deferred_locals(NULL);
1438 set_deopt_mark(NULL);
1439 set_deopt_nmethod(NULL);
1440 clear_must_deopt_id();
1441 set_monitor_chunks(NULL);
1442 set_next(NULL);
1443 set_thread_state(_thread_new);
1444 _terminated = _not_terminated;
1445 _privileged_stack_top = NULL;
1446 _array_for_gc = NULL;
1447 _suspend_equivalent = false;
1448 _in_deopt_handler = 0;
1449 _doing_unsafe_access = false;
1450 _stack_guard_state = stack_guard_unused;
1451 (void)const_cast<oop&>(_exception_oop = NULL);
1452 _exception_pc = 0;
1453 _exception_handler_pc = 0;
1454 _is_method_handle_return = 0;
1455 _jvmti_thread_state= NULL;
1456 _should_post_on_exceptions_flag = JNI_FALSE;
1457 _jvmti_get_loaded_classes_closure = NULL;
1458 _interp_only_mode = 0;
1459 _special_runtime_exit_condition = _no_async_condition;
1460 _pending_async_exception = NULL;
1461 _thread_stat = NULL;
1462 _thread_stat = new ThreadStatistics();
1463 _blocked_on_compilation = false;
1464 _jni_active_critical = 0;
1465 _do_not_unlock_if_synchronized = false;
1466 _cached_monitor_info = NULL;
1467 _parker = Parker::Allocate(this) ;
1469 #ifndef PRODUCT
1470 _jmp_ring_index = 0;
1471 for (int ji = 0 ; ji < jump_ring_buffer_size ; ji++ ) {
1472 record_jump(NULL, NULL, NULL, 0);
1473 }
1474 #endif /* PRODUCT */
1476 set_thread_profiler(NULL);
1477 if (FlatProfiler::is_active()) {
1478 // This is where we would decide to either give each thread it's own profiler
1479 // or use one global one from FlatProfiler,
1480 // or up to some count of the number of profiled threads, etc.
1481 ThreadProfiler* pp = new ThreadProfiler();
1482 pp->engage();
1483 set_thread_profiler(pp);
1484 }
1486 // Setup safepoint state info for this thread
1487 ThreadSafepointState::create(this);
1489 debug_only(_java_call_counter = 0);
1491 // JVMTI PopFrame support
1492 _popframe_condition = popframe_inactive;
1493 _popframe_preserved_args = NULL;
1494 _popframe_preserved_args_size = 0;
1496 pd_initialize();
1497 }
1499 #if INCLUDE_ALL_GCS
1500 SATBMarkQueueSet JavaThread::_satb_mark_queue_set;
1501 DirtyCardQueueSet JavaThread::_dirty_card_queue_set;
1502 #endif // INCLUDE_ALL_GCS
1504 JavaThread::JavaThread(bool is_attaching_via_jni) :
1505 Thread()
1506 #if INCLUDE_ALL_GCS
1507 , _satb_mark_queue(&_satb_mark_queue_set),
1508 _dirty_card_queue(&_dirty_card_queue_set)
1509 #endif // INCLUDE_ALL_GCS
1510 {
1511 initialize();
1512 if (is_attaching_via_jni) {
1513 _jni_attach_state = _attaching_via_jni;
1514 } else {
1515 _jni_attach_state = _not_attaching_via_jni;
1516 }
1517 assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
1518 }
1520 bool JavaThread::reguard_stack(address cur_sp) {
1521 if (_stack_guard_state != stack_guard_yellow_disabled) {
1522 return true; // Stack already guarded or guard pages not needed.
1523 }
1525 if (register_stack_overflow()) {
1526 // For those architectures which have separate register and
1527 // memory stacks, we must check the register stack to see if
1528 // it has overflowed.
1529 return false;
1530 }
1532 // Java code never executes within the yellow zone: the latter is only
1533 // there to provoke an exception during stack banging. If java code
1534 // is executing there, either StackShadowPages should be larger, or
1535 // some exception code in c1, c2 or the interpreter isn't unwinding
1536 // when it should.
1537 guarantee(cur_sp > stack_yellow_zone_base(), "not enough space to reguard - increase StackShadowPages");
1539 enable_stack_yellow_zone();
1540 return true;
1541 }
1543 bool JavaThread::reguard_stack(void) {
1544 return reguard_stack(os::current_stack_pointer());
1545 }
1548 void JavaThread::block_if_vm_exited() {
1549 if (_terminated == _vm_exited) {
1550 // _vm_exited is set at safepoint, and Threads_lock is never released
1551 // we will block here forever
1552 Threads_lock->lock_without_safepoint_check();
1553 ShouldNotReachHere();
1554 }
1555 }
1558 // Remove this ifdef when C1 is ported to the compiler interface.
1559 static void compiler_thread_entry(JavaThread* thread, TRAPS);
1561 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
1562 Thread()
1563 #if INCLUDE_ALL_GCS
1564 , _satb_mark_queue(&_satb_mark_queue_set),
1565 _dirty_card_queue(&_dirty_card_queue_set)
1566 #endif // INCLUDE_ALL_GCS
1567 {
1568 if (TraceThreadEvents) {
1569 tty->print_cr("creating thread %p", this);
1570 }
1571 initialize();
1572 _jni_attach_state = _not_attaching_via_jni;
1573 set_entry_point(entry_point);
1574 // Create the native thread itself.
1575 // %note runtime_23
1576 os::ThreadType thr_type = os::java_thread;
1577 thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
1578 os::java_thread;
1579 os::create_thread(this, thr_type, stack_sz);
1580 // The _osthread may be NULL here because we ran out of memory (too many threads active).
1581 // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
1582 // may hold a lock and all locks must be unlocked before throwing the exception (throwing
1583 // the exception consists of creating the exception object & initializing it, initialization
1584 // will leave the VM via a JavaCall and then all locks must be unlocked).
1585 //
1586 // The thread is still suspended when we reach here. Thread must be explicit started
1587 // by creator! Furthermore, the thread must also explicitly be added to the Threads list
1588 // by calling Threads:add. The reason why this is not done here, is because the thread
1589 // object must be fully initialized (take a look at JVM_Start)
1590 }
1592 JavaThread::~JavaThread() {
1593 if (TraceThreadEvents) {
1594 tty->print_cr("terminate thread %p", this);
1595 }
1597 // JSR166 -- return the parker to the free list
1598 Parker::Release(_parker);
1599 _parker = NULL ;
1601 // Free any remaining previous UnrollBlock
1602 vframeArray* old_array = vframe_array_last();
1604 if (old_array != NULL) {
1605 Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
1606 old_array->set_unroll_block(NULL);
1607 delete old_info;
1608 delete old_array;
1609 }
1611 GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals();
1612 if (deferred != NULL) {
1613 // This can only happen if thread is destroyed before deoptimization occurs.
1614 assert(deferred->length() != 0, "empty array!");
1615 do {
1616 jvmtiDeferredLocalVariableSet* dlv = deferred->at(0);
1617 deferred->remove_at(0);
1618 // individual jvmtiDeferredLocalVariableSet are CHeapObj's
1619 delete dlv;
1620 } while (deferred->length() != 0);
1621 delete deferred;
1622 }
1624 // All Java related clean up happens in exit
1625 ThreadSafepointState::destroy(this);
1626 if (_thread_profiler != NULL) delete _thread_profiler;
1627 if (_thread_stat != NULL) delete _thread_stat;
1628 }
1631 // The first routine called by a new Java thread
1632 void JavaThread::run() {
1633 // initialize thread-local alloc buffer related fields
1634 this->initialize_tlab();
1636 // used to test validitity of stack trace backs
1637 this->record_base_of_stack_pointer();
1639 // Record real stack base and size.
1640 this->record_stack_base_and_size();
1642 // Initialize thread local storage; set before calling MutexLocker
1643 this->initialize_thread_local_storage();
1645 this->create_stack_guard_pages();
1647 this->cache_global_variables();
1649 // Thread is now sufficient initialized to be handled by the safepoint code as being
1650 // in the VM. Change thread state from _thread_new to _thread_in_vm
1651 ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
1653 assert(JavaThread::current() == this, "sanity check");
1654 assert(!Thread::current()->owns_locks(), "sanity check");
1656 DTRACE_THREAD_PROBE(start, this);
1658 // This operation might block. We call that after all safepoint checks for a new thread has
1659 // been completed.
1660 this->set_active_handles(JNIHandleBlock::allocate_block());
1662 if (JvmtiExport::should_post_thread_life()) {
1663 JvmtiExport::post_thread_start(this);
1664 }
1666 EventThreadStart event;
1667 if (event.should_commit()) {
1668 event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj()));
1669 event.commit();
1670 }
1672 // We call another function to do the rest so we are sure that the stack addresses used
1673 // from there will be lower than the stack base just computed
1674 thread_main_inner();
1676 // Note, thread is no longer valid at this point!
1677 }
1680 void JavaThread::thread_main_inner() {
1681 assert(JavaThread::current() == this, "sanity check");
1682 assert(this->threadObj() != NULL, "just checking");
1684 // Execute thread entry point unless this thread has a pending exception
1685 // or has been stopped before starting.
1686 // Note: Due to JVM_StopThread we can have pending exceptions already!
1687 if (!this->has_pending_exception() &&
1688 !java_lang_Thread::is_stillborn(this->threadObj())) {
1689 {
1690 ResourceMark rm(this);
1691 this->set_native_thread_name(this->get_thread_name());
1692 }
1693 HandleMark hm(this);
1694 this->entry_point()(this, this);
1695 }
1697 DTRACE_THREAD_PROBE(stop, this);
1699 this->exit(false);
1700 delete this;
1701 }
1704 static void ensure_join(JavaThread* thread) {
1705 // We do not need to grap the Threads_lock, since we are operating on ourself.
1706 Handle threadObj(thread, thread->threadObj());
1707 assert(threadObj.not_null(), "java thread object must exist");
1708 ObjectLocker lock(threadObj, thread);
1709 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1710 thread->clear_pending_exception();
1711 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
1712 java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1713 // Clear the native thread instance - this makes isAlive return false and allows the join()
1714 // to complete once we've done the notify_all below
1715 java_lang_Thread::set_thread(threadObj(), NULL);
1716 lock.notify_all(thread);
1717 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1718 thread->clear_pending_exception();
1719 }
1722 // For any new cleanup additions, please check to see if they need to be applied to
1723 // cleanup_failed_attach_current_thread as well.
1724 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
1725 assert(this == JavaThread::current(), "thread consistency check");
1727 HandleMark hm(this);
1728 Handle uncaught_exception(this, this->pending_exception());
1729 this->clear_pending_exception();
1730 Handle threadObj(this, this->threadObj());
1731 assert(threadObj.not_null(), "Java thread object should be created");
1733 if (get_thread_profiler() != NULL) {
1734 get_thread_profiler()->disengage();
1735 ResourceMark rm;
1736 get_thread_profiler()->print(get_thread_name());
1737 }
1740 // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place
1741 {
1742 EXCEPTION_MARK;
1744 CLEAR_PENDING_EXCEPTION;
1745 }
1746 // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This
1747 // has to be fixed by a runtime query method
1748 if (!destroy_vm || JDK_Version::is_jdk12x_version()) {
1749 // JSR-166: change call from from ThreadGroup.uncaughtException to
1750 // java.lang.Thread.dispatchUncaughtException
1751 if (uncaught_exception.not_null()) {
1752 Handle group(this, java_lang_Thread::threadGroup(threadObj()));
1753 {
1754 EXCEPTION_MARK;
1755 // Check if the method Thread.dispatchUncaughtException() exists. If so
1756 // call it. Otherwise we have an older library without the JSR-166 changes,
1757 // so call ThreadGroup.uncaughtException()
1758 KlassHandle recvrKlass(THREAD, threadObj->klass());
1759 CallInfo callinfo;
1760 KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
1761 LinkResolver::resolve_virtual_call(callinfo, threadObj, recvrKlass, thread_klass,
1762 vmSymbols::dispatchUncaughtException_name(),
1763 vmSymbols::throwable_void_signature(),
1764 KlassHandle(), false, false, THREAD);
1765 CLEAR_PENDING_EXCEPTION;
1766 methodHandle method = callinfo.selected_method();
1767 if (method.not_null()) {
1768 JavaValue result(T_VOID);
1769 JavaCalls::call_virtual(&result,
1770 threadObj, thread_klass,
1771 vmSymbols::dispatchUncaughtException_name(),
1772 vmSymbols::throwable_void_signature(),
1773 uncaught_exception,
1774 THREAD);
1775 } else {
1776 KlassHandle thread_group(THREAD, SystemDictionary::ThreadGroup_klass());
1777 JavaValue result(T_VOID);
1778 JavaCalls::call_virtual(&result,
1779 group, thread_group,
1780 vmSymbols::uncaughtException_name(),
1781 vmSymbols::thread_throwable_void_signature(),
1782 threadObj, // Arg 1
1783 uncaught_exception, // Arg 2
1784 THREAD);
1785 }
1786 if (HAS_PENDING_EXCEPTION) {
1787 ResourceMark rm(this);
1788 jio_fprintf(defaultStream::error_stream(),
1789 "\nException: %s thrown from the UncaughtExceptionHandler"
1790 " in thread \"%s\"\n",
1791 pending_exception()->klass()->external_name(),
1792 get_thread_name());
1793 CLEAR_PENDING_EXCEPTION;
1794 }
1795 }
1796 }
1798 // Called before the java thread exit since we want to read info
1799 // from java_lang_Thread object
1800 EventThreadEnd event;
1801 if (event.should_commit()) {
1802 event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj()));
1803 event.commit();
1804 }
1806 // Call after last event on thread
1807 EVENT_THREAD_EXIT(this);
1809 // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
1810 // the execution of the method. If that is not enough, then we don't really care. Thread.stop
1811 // is deprecated anyhow.
1812 if (!is_Compiler_thread()) {
1813 int count = 3;
1814 while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
1815 EXCEPTION_MARK;
1816 JavaValue result(T_VOID);
1817 KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
1818 JavaCalls::call_virtual(&result,
1819 threadObj, thread_klass,
1820 vmSymbols::exit_method_name(),
1821 vmSymbols::void_method_signature(),
1822 THREAD);
1823 CLEAR_PENDING_EXCEPTION;
1824 }
1825 }
1826 // notify JVMTI
1827 if (JvmtiExport::should_post_thread_life()) {
1828 JvmtiExport::post_thread_end(this);
1829 }
1831 // We have notified the agents that we are exiting, before we go on,
1832 // we must check for a pending external suspend request and honor it
1833 // in order to not surprise the thread that made the suspend request.
1834 while (true) {
1835 {
1836 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1837 if (!is_external_suspend()) {
1838 set_terminated(_thread_exiting);
1839 ThreadService::current_thread_exiting(this);
1840 break;
1841 }
1842 // Implied else:
1843 // Things get a little tricky here. We have a pending external
1844 // suspend request, but we are holding the SR_lock so we
1845 // can't just self-suspend. So we temporarily drop the lock
1846 // and then self-suspend.
1847 }
1849 ThreadBlockInVM tbivm(this);
1850 java_suspend_self();
1852 // We're done with this suspend request, but we have to loop around
1853 // and check again. Eventually we will get SR_lock without a pending
1854 // external suspend request and will be able to mark ourselves as
1855 // exiting.
1856 }
1857 // no more external suspends are allowed at this point
1858 } else {
1859 // before_exit() has already posted JVMTI THREAD_END events
1860 }
1862 // Notify waiters on thread object. This has to be done after exit() is called
1863 // on the thread (if the thread is the last thread in a daemon ThreadGroup the
1864 // group should have the destroyed bit set before waiters are notified).
1865 ensure_join(this);
1866 assert(!this->has_pending_exception(), "ensure_join should have cleared");
1868 // 6282335 JNI DetachCurrentThread spec states that all Java monitors
1869 // held by this thread must be released. A detach operation must only
1870 // get here if there are no Java frames on the stack. Therefore, any
1871 // owned monitors at this point MUST be JNI-acquired monitors which are
1872 // pre-inflated and in the monitor cache.
1873 //
1874 // ensure_join() ignores IllegalThreadStateExceptions, and so does this.
1875 if (exit_type == jni_detach && JNIDetachReleasesMonitors) {
1876 assert(!this->has_last_Java_frame(), "detaching with Java frames?");
1877 ObjectSynchronizer::release_monitors_owned_by_thread(this);
1878 assert(!this->has_pending_exception(), "release_monitors should have cleared");
1879 }
1881 // These things needs to be done while we are still a Java Thread. Make sure that thread
1882 // is in a consistent state, in case GC happens
1883 assert(_privileged_stack_top == NULL, "must be NULL when we get here");
1885 if (active_handles() != NULL) {
1886 JNIHandleBlock* block = active_handles();
1887 set_active_handles(NULL);
1888 JNIHandleBlock::release_block(block);
1889 }
1891 if (free_handle_block() != NULL) {
1892 JNIHandleBlock* block = free_handle_block();
1893 set_free_handle_block(NULL);
1894 JNIHandleBlock::release_block(block);
1895 }
1897 // These have to be removed while this is still a valid thread.
1898 remove_stack_guard_pages();
1900 if (UseTLAB) {
1901 tlab().make_parsable(true); // retire TLAB
1902 }
1904 if (JvmtiEnv::environments_might_exist()) {
1905 JvmtiExport::cleanup_thread(this);
1906 }
1908 // We must flush any deferred card marks before removing a thread from
1909 // the list of active threads.
1910 Universe::heap()->flush_deferred_store_barrier(this);
1911 assert(deferred_card_mark().is_empty(), "Should have been flushed");
1913 #if INCLUDE_ALL_GCS
1914 // We must flush the G1-related buffers before removing a thread
1915 // from the list of active threads. We must do this after any deferred
1916 // card marks have been flushed (above) so that any entries that are
1917 // added to the thread's dirty card queue as a result are not lost.
1918 if (UseG1GC) {
1919 flush_barrier_queues();
1920 }
1921 #endif // INCLUDE_ALL_GCS
1923 // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
1924 Threads::remove(this);
1925 }
1927 #if INCLUDE_ALL_GCS
1928 // Flush G1-related queues.
1929 void JavaThread::flush_barrier_queues() {
1930 satb_mark_queue().flush();
1931 dirty_card_queue().flush();
1932 }
1934 void JavaThread::initialize_queues() {
1935 assert(!SafepointSynchronize::is_at_safepoint(),
1936 "we should not be at a safepoint");
1938 ObjPtrQueue& satb_queue = satb_mark_queue();
1939 SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set();
1940 // The SATB queue should have been constructed with its active
1941 // field set to false.
1942 assert(!satb_queue.is_active(), "SATB queue should not be active");
1943 assert(satb_queue.is_empty(), "SATB queue should be empty");
1944 // If we are creating the thread during a marking cycle, we should
1945 // set the active field of the SATB queue to true.
1946 if (satb_queue_set.is_active()) {
1947 satb_queue.set_active(true);
1948 }
1950 DirtyCardQueue& dirty_queue = dirty_card_queue();
1951 // The dirty card queue should have been constructed with its
1952 // active field set to true.
1953 assert(dirty_queue.is_active(), "dirty card queue should be active");
1954 }
1955 #endif // INCLUDE_ALL_GCS
1957 void JavaThread::cleanup_failed_attach_current_thread() {
1958 if (get_thread_profiler() != NULL) {
1959 get_thread_profiler()->disengage();
1960 ResourceMark rm;
1961 get_thread_profiler()->print(get_thread_name());
1962 }
1964 if (active_handles() != NULL) {
1965 JNIHandleBlock* block = active_handles();
1966 set_active_handles(NULL);
1967 JNIHandleBlock::release_block(block);
1968 }
1970 if (free_handle_block() != NULL) {
1971 JNIHandleBlock* block = free_handle_block();
1972 set_free_handle_block(NULL);
1973 JNIHandleBlock::release_block(block);
1974 }
1976 // These have to be removed while this is still a valid thread.
1977 remove_stack_guard_pages();
1979 if (UseTLAB) {
1980 tlab().make_parsable(true); // retire TLAB, if any
1981 }
1983 #if INCLUDE_ALL_GCS
1984 if (UseG1GC) {
1985 flush_barrier_queues();
1986 }
1987 #endif // INCLUDE_ALL_GCS
1989 Threads::remove(this);
1990 delete this;
1991 }
1996 JavaThread* JavaThread::active() {
1997 Thread* thread = ThreadLocalStorage::thread();
1998 assert(thread != NULL, "just checking");
1999 if (thread->is_Java_thread()) {
2000 return (JavaThread*) thread;
2001 } else {
2002 assert(thread->is_VM_thread(), "this must be a vm thread");
2003 VM_Operation* op = ((VMThread*) thread)->vm_operation();
2004 JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
2005 assert(ret->is_Java_thread(), "must be a Java thread");
2006 return ret;
2007 }
2008 }
2010 bool JavaThread::is_lock_owned(address adr) const {
2011 if (Thread::is_lock_owned(adr)) return true;
2013 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2014 if (chunk->contains(adr)) return true;
2015 }
2017 return false;
2018 }
2021 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
2022 chunk->set_next(monitor_chunks());
2023 set_monitor_chunks(chunk);
2024 }
2026 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
2027 guarantee(monitor_chunks() != NULL, "must be non empty");
2028 if (monitor_chunks() == chunk) {
2029 set_monitor_chunks(chunk->next());
2030 } else {
2031 MonitorChunk* prev = monitor_chunks();
2032 while (prev->next() != chunk) prev = prev->next();
2033 prev->set_next(chunk->next());
2034 }
2035 }
2037 // JVM support.
2039 // Note: this function shouldn't block if it's called in
2040 // _thread_in_native_trans state (such as from
2041 // check_special_condition_for_native_trans()).
2042 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) {
2044 if (has_last_Java_frame() && has_async_condition()) {
2045 // If we are at a polling page safepoint (not a poll return)
2046 // then we must defer async exception because live registers
2047 // will be clobbered by the exception path. Poll return is
2048 // ok because the call we a returning from already collides
2049 // with exception handling registers and so there is no issue.
2050 // (The exception handling path kills call result registers but
2051 // this is ok since the exception kills the result anyway).
2053 if (is_at_poll_safepoint()) {
2054 // if the code we are returning to has deoptimized we must defer
2055 // the exception otherwise live registers get clobbered on the
2056 // exception path before deoptimization is able to retrieve them.
2057 //
2058 RegisterMap map(this, false);
2059 frame caller_fr = last_frame().sender(&map);
2060 assert(caller_fr.is_compiled_frame(), "what?");
2061 if (caller_fr.is_deoptimized_frame()) {
2062 if (TraceExceptions) {
2063 ResourceMark rm;
2064 tty->print_cr("deferred async exception at compiled safepoint");
2065 }
2066 return;
2067 }
2068 }
2069 }
2071 JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition();
2072 if (condition == _no_async_condition) {
2073 // Conditions have changed since has_special_runtime_exit_condition()
2074 // was called:
2075 // - if we were here only because of an external suspend request,
2076 // then that was taken care of above (or cancelled) so we are done
2077 // - if we were here because of another async request, then it has
2078 // been cleared between the has_special_runtime_exit_condition()
2079 // and now so again we are done
2080 return;
2081 }
2083 // Check for pending async. exception
2084 if (_pending_async_exception != NULL) {
2085 // Only overwrite an already pending exception, if it is not a threadDeath.
2086 if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) {
2088 // We cannot call Exceptions::_throw(...) here because we cannot block
2089 set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
2091 if (TraceExceptions) {
2092 ResourceMark rm;
2093 tty->print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", this);
2094 if (has_last_Java_frame() ) {
2095 frame f = last_frame();
2096 tty->print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", f.pc(), f.sp());
2097 }
2098 tty->print_cr(" of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name());
2099 }
2100 _pending_async_exception = NULL;
2101 clear_has_async_exception();
2102 }
2103 }
2105 if (check_unsafe_error &&
2106 condition == _async_unsafe_access_error && !has_pending_exception()) {
2107 condition = _no_async_condition; // done
2108 switch (thread_state()) {
2109 case _thread_in_vm:
2110 {
2111 JavaThread* THREAD = this;
2112 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
2113 }
2114 case _thread_in_native:
2115 {
2116 ThreadInVMfromNative tiv(this);
2117 JavaThread* THREAD = this;
2118 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
2119 }
2120 case _thread_in_Java:
2121 {
2122 ThreadInVMfromJava tiv(this);
2123 JavaThread* THREAD = this;
2124 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
2125 }
2126 default:
2127 ShouldNotReachHere();
2128 }
2129 }
2131 assert(condition == _no_async_condition || has_pending_exception() ||
2132 (!check_unsafe_error && condition == _async_unsafe_access_error),
2133 "must have handled the async condition, if no exception");
2134 }
2136 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
2137 //
2138 // Check for pending external suspend. Internal suspend requests do
2139 // not use handle_special_runtime_exit_condition().
2140 // If JNIEnv proxies are allowed, don't self-suspend if the target
2141 // thread is not the current thread. In older versions of jdbx, jdbx
2142 // threads could call into the VM with another thread's JNIEnv so we
2143 // can be here operating on behalf of a suspended thread (4432884).
2144 bool do_self_suspend = is_external_suspend_with_lock();
2145 if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) {
2146 //
2147 // Because thread is external suspended the safepoint code will count
2148 // thread as at a safepoint. This can be odd because we can be here
2149 // as _thread_in_Java which would normally transition to _thread_blocked
2150 // at a safepoint. We would like to mark the thread as _thread_blocked
2151 // before calling java_suspend_self like all other callers of it but
2152 // we must then observe proper safepoint protocol. (We can't leave
2153 // _thread_blocked with a safepoint in progress). However we can be
2154 // here as _thread_in_native_trans so we can't use a normal transition
2155 // constructor/destructor pair because they assert on that type of
2156 // transition. We could do something like:
2157 //
2158 // JavaThreadState state = thread_state();
2159 // set_thread_state(_thread_in_vm);
2160 // {
2161 // ThreadBlockInVM tbivm(this);
2162 // java_suspend_self()
2163 // }
2164 // set_thread_state(_thread_in_vm_trans);
2165 // if (safepoint) block;
2166 // set_thread_state(state);
2167 //
2168 // but that is pretty messy. Instead we just go with the way the
2169 // code has worked before and note that this is the only path to
2170 // java_suspend_self that doesn't put the thread in _thread_blocked
2171 // mode.
2173 frame_anchor()->make_walkable(this);
2174 java_suspend_self();
2176 // We might be here for reasons in addition to the self-suspend request
2177 // so check for other async requests.
2178 }
2180 if (check_asyncs) {
2181 check_and_handle_async_exceptions();
2182 }
2183 }
2185 void JavaThread::send_thread_stop(oop java_throwable) {
2186 assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
2187 assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
2188 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
2190 // Do not throw asynchronous exceptions against the compiler thread
2191 // (the compiler thread should not be a Java thread -- fix in 1.4.2)
2192 if (is_Compiler_thread()) return;
2194 {
2195 // Actually throw the Throwable against the target Thread - however
2196 // only if there is no thread death exception installed already.
2197 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
2198 // If the topmost frame is a runtime stub, then we are calling into
2199 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
2200 // must deoptimize the caller before continuing, as the compiled exception handler table
2201 // may not be valid
2202 if (has_last_Java_frame()) {
2203 frame f = last_frame();
2204 if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
2205 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2206 RegisterMap reg_map(this, UseBiasedLocking);
2207 frame compiled_frame = f.sender(®_map);
2208 if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
2209 Deoptimization::deoptimize(this, compiled_frame, ®_map);
2210 }
2211 }
2212 }
2214 // Set async. pending exception in thread.
2215 set_pending_async_exception(java_throwable);
2217 if (TraceExceptions) {
2218 ResourceMark rm;
2219 tty->print_cr("Pending Async. exception installed of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name());
2220 }
2221 // for AbortVMOnException flag
2222 NOT_PRODUCT(Exceptions::debug_check_abort(InstanceKlass::cast(_pending_async_exception->klass())->external_name()));
2223 }
2224 }
2227 // Interrupt thread so it will wake up from a potential wait()
2228 Thread::interrupt(this);
2229 }
2231 // External suspension mechanism.
2232 //
2233 // Tell the VM to suspend a thread when ever it knows that it does not hold on
2234 // to any VM_locks and it is at a transition
2235 // Self-suspension will happen on the transition out of the vm.
2236 // Catch "this" coming in from JNIEnv pointers when the thread has been freed
2237 //
2238 // Guarantees on return:
2239 // + Target thread will not execute any new bytecode (that's why we need to
2240 // force a safepoint)
2241 // + Target thread will not enter any new monitors
2242 //
2243 void JavaThread::java_suspend() {
2244 { MutexLocker mu(Threads_lock);
2245 if (!Threads::includes(this) || is_exiting() || this->threadObj() == NULL) {
2246 return;
2247 }
2248 }
2250 { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2251 if (!is_external_suspend()) {
2252 // a racing resume has cancelled us; bail out now
2253 return;
2254 }
2256 // suspend is done
2257 uint32_t debug_bits = 0;
2258 // Warning: is_ext_suspend_completed() may temporarily drop the
2259 // SR_lock to allow the thread to reach a stable thread state if
2260 // it is currently in a transient thread state.
2261 if (is_ext_suspend_completed(false /* !called_by_wait */,
2262 SuspendRetryDelay, &debug_bits) ) {
2263 return;
2264 }
2265 }
2267 VM_ForceSafepoint vm_suspend;
2268 VMThread::execute(&vm_suspend);
2269 }
2271 // Part II of external suspension.
2272 // A JavaThread self suspends when it detects a pending external suspend
2273 // request. This is usually on transitions. It is also done in places
2274 // where continuing to the next transition would surprise the caller,
2275 // e.g., monitor entry.
2276 //
2277 // Returns the number of times that the thread self-suspended.
2278 //
2279 // Note: DO NOT call java_suspend_self() when you just want to block current
2280 // thread. java_suspend_self() is the second stage of cooperative
2281 // suspension for external suspend requests and should only be used
2282 // to complete an external suspend request.
2283 //
2284 int JavaThread::java_suspend_self() {
2285 int ret = 0;
2287 // we are in the process of exiting so don't suspend
2288 if (is_exiting()) {
2289 clear_external_suspend();
2290 return ret;
2291 }
2293 assert(_anchor.walkable() ||
2294 (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()),
2295 "must have walkable stack");
2297 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2299 assert(!this->is_ext_suspended(),
2300 "a thread trying to self-suspend should not already be suspended");
2302 if (this->is_suspend_equivalent()) {
2303 // If we are self-suspending as a result of the lifting of a
2304 // suspend equivalent condition, then the suspend_equivalent
2305 // flag is not cleared until we set the ext_suspended flag so
2306 // that wait_for_ext_suspend_completion() returns consistent
2307 // results.
2308 this->clear_suspend_equivalent();
2309 }
2311 // A racing resume may have cancelled us before we grabbed SR_lock
2312 // above. Or another external suspend request could be waiting for us
2313 // by the time we return from SR_lock()->wait(). The thread
2314 // that requested the suspension may already be trying to walk our
2315 // stack and if we return now, we can change the stack out from under
2316 // it. This would be a "bad thing (TM)" and cause the stack walker
2317 // to crash. We stay self-suspended until there are no more pending
2318 // external suspend requests.
2319 while (is_external_suspend()) {
2320 ret++;
2321 this->set_ext_suspended();
2323 // _ext_suspended flag is cleared by java_resume()
2324 while (is_ext_suspended()) {
2325 this->SR_lock()->wait(Mutex::_no_safepoint_check_flag);
2326 }
2327 }
2329 return ret;
2330 }
2332 #ifdef ASSERT
2333 // verify the JavaThread has not yet been published in the Threads::list, and
2334 // hence doesn't need protection from concurrent access at this stage
2335 void JavaThread::verify_not_published() {
2336 if (!Threads_lock->owned_by_self()) {
2337 MutexLockerEx ml(Threads_lock, Mutex::_no_safepoint_check_flag);
2338 assert( !Threads::includes(this),
2339 "java thread shouldn't have been published yet!");
2340 }
2341 else {
2342 assert( !Threads::includes(this),
2343 "java thread shouldn't have been published yet!");
2344 }
2345 }
2346 #endif
2348 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2349 // progress or when _suspend_flags is non-zero.
2350 // Current thread needs to self-suspend if there is a suspend request and/or
2351 // block if a safepoint is in progress.
2352 // Async exception ISN'T checked.
2353 // Note only the ThreadInVMfromNative transition can call this function
2354 // directly and when thread state is _thread_in_native_trans
2355 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
2356 assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
2358 JavaThread *curJT = JavaThread::current();
2359 bool do_self_suspend = thread->is_external_suspend();
2361 assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
2363 // If JNIEnv proxies are allowed, don't self-suspend if the target
2364 // thread is not the current thread. In older versions of jdbx, jdbx
2365 // threads could call into the VM with another thread's JNIEnv so we
2366 // can be here operating on behalf of a suspended thread (4432884).
2367 if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) {
2368 JavaThreadState state = thread->thread_state();
2370 // We mark this thread_blocked state as a suspend-equivalent so
2371 // that a caller to is_ext_suspend_completed() won't be confused.
2372 // The suspend-equivalent state is cleared by java_suspend_self().
2373 thread->set_suspend_equivalent();
2375 // If the safepoint code sees the _thread_in_native_trans state, it will
2376 // wait until the thread changes to other thread state. There is no
2377 // guarantee on how soon we can obtain the SR_lock and complete the
2378 // self-suspend request. It would be a bad idea to let safepoint wait for
2379 // too long. Temporarily change the state to _thread_blocked to
2380 // let the VM thread know that this thread is ready for GC. The problem
2381 // of changing thread state is that safepoint could happen just after
2382 // java_suspend_self() returns after being resumed, and VM thread will
2383 // see the _thread_blocked state. We must check for safepoint
2384 // after restoring the state and make sure we won't leave while a safepoint
2385 // is in progress.
2386 thread->set_thread_state(_thread_blocked);
2387 thread->java_suspend_self();
2388 thread->set_thread_state(state);
2389 // Make sure new state is seen by VM thread
2390 if (os::is_MP()) {
2391 if (UseMembar) {
2392 // Force a fence between the write above and read below
2393 OrderAccess::fence();
2394 } else {
2395 // Must use this rather than serialization page in particular on Windows
2396 InterfaceSupport::serialize_memory(thread);
2397 }
2398 }
2399 }
2401 if (SafepointSynchronize::do_call_back()) {
2402 // If we are safepointing, then block the caller which may not be
2403 // the same as the target thread (see above).
2404 SafepointSynchronize::block(curJT);
2405 }
2407 if (thread->is_deopt_suspend()) {
2408 thread->clear_deopt_suspend();
2409 RegisterMap map(thread, false);
2410 frame f = thread->last_frame();
2411 while ( f.id() != thread->must_deopt_id() && ! f.is_first_frame()) {
2412 f = f.sender(&map);
2413 }
2414 if (f.id() == thread->must_deopt_id()) {
2415 thread->clear_must_deopt_id();
2416 f.deoptimize(thread);
2417 } else {
2418 fatal("missed deoptimization!");
2419 }
2420 }
2421 }
2423 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2424 // progress or when _suspend_flags is non-zero.
2425 // Current thread needs to self-suspend if there is a suspend request and/or
2426 // block if a safepoint is in progress.
2427 // Also check for pending async exception (not including unsafe access error).
2428 // Note only the native==>VM/Java barriers can call this function and when
2429 // thread state is _thread_in_native_trans.
2430 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
2431 check_safepoint_and_suspend_for_native_trans(thread);
2433 if (thread->has_async_exception()) {
2434 // We are in _thread_in_native_trans state, don't handle unsafe
2435 // access error since that may block.
2436 thread->check_and_handle_async_exceptions(false);
2437 }
2438 }
2440 // This is a variant of the normal
2441 // check_special_condition_for_native_trans with slightly different
2442 // semantics for use by critical native wrappers. It does all the
2443 // normal checks but also performs the transition back into
2444 // thread_in_Java state. This is required so that critical natives
2445 // can potentially block and perform a GC if they are the last thread
2446 // exiting the GC_locker.
2447 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) {
2448 check_special_condition_for_native_trans(thread);
2450 // Finish the transition
2451 thread->set_thread_state(_thread_in_Java);
2453 if (thread->do_critical_native_unlock()) {
2454 ThreadInVMfromJavaNoAsyncException tiv(thread);
2455 GC_locker::unlock_critical(thread);
2456 thread->clear_critical_native_unlock();
2457 }
2458 }
2460 // We need to guarantee the Threads_lock here, since resumes are not
2461 // allowed during safepoint synchronization
2462 // Can only resume from an external suspension
2463 void JavaThread::java_resume() {
2464 assert_locked_or_safepoint(Threads_lock);
2466 // Sanity check: thread is gone, has started exiting or the thread
2467 // was not externally suspended.
2468 if (!Threads::includes(this) || is_exiting() || !is_external_suspend()) {
2469 return;
2470 }
2472 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2474 clear_external_suspend();
2476 if (is_ext_suspended()) {
2477 clear_ext_suspended();
2478 SR_lock()->notify_all();
2479 }
2480 }
2482 void JavaThread::create_stack_guard_pages() {
2483 if (! os::uses_stack_guard_pages() || _stack_guard_state != stack_guard_unused) return;
2484 address low_addr = stack_base() - stack_size();
2485 size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
2487 int allocate = os::allocate_stack_guard_pages();
2488 // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len);
2490 if (allocate && !os::create_stack_guard_pages((char *) low_addr, len)) {
2491 warning("Attempt to allocate stack guard pages failed.");
2492 return;
2493 }
2495 if (os::guard_memory((char *) low_addr, len)) {
2496 _stack_guard_state = stack_guard_enabled;
2497 } else {
2498 warning("Attempt to protect stack guard pages failed.");
2499 if (os::uncommit_memory((char *) low_addr, len)) {
2500 warning("Attempt to deallocate stack guard pages failed.");
2501 }
2502 }
2503 }
2505 void JavaThread::remove_stack_guard_pages() {
2506 assert(Thread::current() == this, "from different thread");
2507 if (_stack_guard_state == stack_guard_unused) return;
2508 address low_addr = stack_base() - stack_size();
2509 size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
2511 if (os::allocate_stack_guard_pages()) {
2512 if (os::remove_stack_guard_pages((char *) low_addr, len)) {
2513 _stack_guard_state = stack_guard_unused;
2514 } else {
2515 warning("Attempt to deallocate stack guard pages failed.");
2516 }
2517 } else {
2518 if (_stack_guard_state == stack_guard_unused) return;
2519 if (os::unguard_memory((char *) low_addr, len)) {
2520 _stack_guard_state = stack_guard_unused;
2521 } else {
2522 warning("Attempt to unprotect stack guard pages failed.");
2523 }
2524 }
2525 }
2527 void JavaThread::enable_stack_yellow_zone() {
2528 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2529 assert(_stack_guard_state != stack_guard_enabled, "already enabled");
2531 // The base notation is from the stacks point of view, growing downward.
2532 // We need to adjust it to work correctly with guard_memory()
2533 address base = stack_yellow_zone_base() - stack_yellow_zone_size();
2535 guarantee(base < stack_base(),"Error calculating stack yellow zone");
2536 guarantee(base < os::current_stack_pointer(),"Error calculating stack yellow zone");
2538 if (os::guard_memory((char *) base, stack_yellow_zone_size())) {
2539 _stack_guard_state = stack_guard_enabled;
2540 } else {
2541 warning("Attempt to guard stack yellow zone failed.");
2542 }
2543 enable_register_stack_guard();
2544 }
2546 void JavaThread::disable_stack_yellow_zone() {
2547 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2548 assert(_stack_guard_state != stack_guard_yellow_disabled, "already disabled");
2550 // Simply return if called for a thread that does not use guard pages.
2551 if (_stack_guard_state == stack_guard_unused) return;
2553 // The base notation is from the stacks point of view, growing downward.
2554 // We need to adjust it to work correctly with guard_memory()
2555 address base = stack_yellow_zone_base() - stack_yellow_zone_size();
2557 if (os::unguard_memory((char *)base, stack_yellow_zone_size())) {
2558 _stack_guard_state = stack_guard_yellow_disabled;
2559 } else {
2560 warning("Attempt to unguard stack yellow zone failed.");
2561 }
2562 disable_register_stack_guard();
2563 }
2565 void JavaThread::enable_stack_red_zone() {
2566 // The base notation is from the stacks point of view, growing downward.
2567 // We need to adjust it to work correctly with guard_memory()
2568 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2569 address base = stack_red_zone_base() - stack_red_zone_size();
2571 guarantee(base < stack_base(),"Error calculating stack red zone");
2572 guarantee(base < os::current_stack_pointer(),"Error calculating stack red zone");
2574 if(!os::guard_memory((char *) base, stack_red_zone_size())) {
2575 warning("Attempt to guard stack red zone failed.");
2576 }
2577 }
2579 void JavaThread::disable_stack_red_zone() {
2580 // The base notation is from the stacks point of view, growing downward.
2581 // We need to adjust it to work correctly with guard_memory()
2582 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2583 address base = stack_red_zone_base() - stack_red_zone_size();
2584 if (!os::unguard_memory((char *)base, stack_red_zone_size())) {
2585 warning("Attempt to unguard stack red zone failed.");
2586 }
2587 }
2589 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
2590 // ignore is there is no stack
2591 if (!has_last_Java_frame()) return;
2592 // traverse the stack frames. Starts from top frame.
2593 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2594 frame* fr = fst.current();
2595 f(fr, fst.register_map());
2596 }
2597 }
2600 #ifndef PRODUCT
2601 // Deoptimization
2602 // Function for testing deoptimization
2603 void JavaThread::deoptimize() {
2604 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2605 StackFrameStream fst(this, UseBiasedLocking);
2606 bool deopt = false; // Dump stack only if a deopt actually happens.
2607 bool only_at = strlen(DeoptimizeOnlyAt) > 0;
2608 // Iterate over all frames in the thread and deoptimize
2609 for(; !fst.is_done(); fst.next()) {
2610 if(fst.current()->can_be_deoptimized()) {
2612 if (only_at) {
2613 // Deoptimize only at particular bcis. DeoptimizeOnlyAt
2614 // consists of comma or carriage return separated numbers so
2615 // search for the current bci in that string.
2616 address pc = fst.current()->pc();
2617 nmethod* nm = (nmethod*) fst.current()->cb();
2618 ScopeDesc* sd = nm->scope_desc_at( pc);
2619 char buffer[8];
2620 jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
2621 size_t len = strlen(buffer);
2622 const char * found = strstr(DeoptimizeOnlyAt, buffer);
2623 while (found != NULL) {
2624 if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
2625 (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
2626 // Check that the bci found is bracketed by terminators.
2627 break;
2628 }
2629 found = strstr(found + 1, buffer);
2630 }
2631 if (!found) {
2632 continue;
2633 }
2634 }
2636 if (DebugDeoptimization && !deopt) {
2637 deopt = true; // One-time only print before deopt
2638 tty->print_cr("[BEFORE Deoptimization]");
2639 trace_frames();
2640 trace_stack();
2641 }
2642 Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2643 }
2644 }
2646 if (DebugDeoptimization && deopt) {
2647 tty->print_cr("[AFTER Deoptimization]");
2648 trace_frames();
2649 }
2650 }
2653 // Make zombies
2654 void JavaThread::make_zombies() {
2655 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2656 if (fst.current()->can_be_deoptimized()) {
2657 // it is a Java nmethod
2658 nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
2659 nm->make_not_entrant();
2660 }
2661 }
2662 }
2663 #endif // PRODUCT
2666 void JavaThread::deoptimized_wrt_marked_nmethods() {
2667 if (!has_last_Java_frame()) return;
2668 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2669 StackFrameStream fst(this, UseBiasedLocking);
2670 for(; !fst.is_done(); fst.next()) {
2671 if (fst.current()->should_be_deoptimized()) {
2672 if (LogCompilation && xtty != NULL) {
2673 nmethod* nm = fst.current()->cb()->as_nmethod_or_null();
2674 xtty->elem("deoptimized thread='" UINTX_FORMAT "' compile_id='%d'",
2675 this->name(), nm != NULL ? nm->compile_id() : -1);
2676 }
2678 Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2679 }
2680 }
2681 }
2684 // GC support
2685 static void frame_gc_epilogue(frame* f, const RegisterMap* map) { f->gc_epilogue(); }
2687 void JavaThread::gc_epilogue() {
2688 frames_do(frame_gc_epilogue);
2689 }
2692 static void frame_gc_prologue(frame* f, const RegisterMap* map) { f->gc_prologue(); }
2694 void JavaThread::gc_prologue() {
2695 frames_do(frame_gc_prologue);
2696 }
2698 // If the caller is a NamedThread, then remember, in the current scope,
2699 // the given JavaThread in its _processed_thread field.
2700 class RememberProcessedThread: public StackObj {
2701 NamedThread* _cur_thr;
2702 public:
2703 RememberProcessedThread(JavaThread* jthr) {
2704 Thread* thread = Thread::current();
2705 if (thread->is_Named_thread()) {
2706 _cur_thr = (NamedThread *)thread;
2707 _cur_thr->set_processed_thread(jthr);
2708 } else {
2709 _cur_thr = NULL;
2710 }
2711 }
2713 ~RememberProcessedThread() {
2714 if (_cur_thr) {
2715 _cur_thr->set_processed_thread(NULL);
2716 }
2717 }
2718 };
2720 void JavaThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
2721 // Verify that the deferred card marks have been flushed.
2722 assert(deferred_card_mark().is_empty(), "Should be empty during GC");
2724 // The ThreadProfiler oops_do is done from FlatProfiler::oops_do
2725 // since there may be more than one thread using each ThreadProfiler.
2727 // Traverse the GCHandles
2728 Thread::oops_do(f, cld_f, cf);
2730 assert( (!has_last_Java_frame() && java_call_counter() == 0) ||
2731 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2733 if (has_last_Java_frame()) {
2734 // Record JavaThread to GC thread
2735 RememberProcessedThread rpt(this);
2737 // Traverse the privileged stack
2738 if (_privileged_stack_top != NULL) {
2739 _privileged_stack_top->oops_do(f);
2740 }
2742 // traverse the registered growable array
2743 if (_array_for_gc != NULL) {
2744 for (int index = 0; index < _array_for_gc->length(); index++) {
2745 f->do_oop(_array_for_gc->adr_at(index));
2746 }
2747 }
2749 // Traverse the monitor chunks
2750 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2751 chunk->oops_do(f);
2752 }
2754 // Traverse the execution stack
2755 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2756 fst.current()->oops_do(f, cld_f, cf, fst.register_map());
2757 }
2758 }
2760 // callee_target is never live across a gc point so NULL it here should
2761 // it still contain a methdOop.
2763 set_callee_target(NULL);
2765 assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
2766 // If we have deferred set_locals there might be oops waiting to be
2767 // written
2768 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals();
2769 if (list != NULL) {
2770 for (int i = 0; i < list->length(); i++) {
2771 list->at(i)->oops_do(f);
2772 }
2773 }
2775 // Traverse instance variables at the end since the GC may be moving things
2776 // around using this function
2777 f->do_oop((oop*) &_threadObj);
2778 f->do_oop((oop*) &_vm_result);
2779 f->do_oop((oop*) &_exception_oop);
2780 f->do_oop((oop*) &_pending_async_exception);
2782 if (jvmti_thread_state() != NULL) {
2783 jvmti_thread_state()->oops_do(f);
2784 }
2785 }
2787 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
2788 Thread::nmethods_do(cf); // (super method is a no-op)
2790 assert( (!has_last_Java_frame() && java_call_counter() == 0) ||
2791 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2793 if (has_last_Java_frame()) {
2794 // Traverse the execution stack
2795 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2796 fst.current()->nmethods_do(cf);
2797 }
2798 }
2799 }
2801 void JavaThread::metadata_do(void f(Metadata*)) {
2802 Thread::metadata_do(f);
2803 if (has_last_Java_frame()) {
2804 // Traverse the execution stack to call f() on the methods in the stack
2805 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2806 fst.current()->metadata_do(f);
2807 }
2808 } else if (is_Compiler_thread()) {
2809 // need to walk ciMetadata in current compile tasks to keep alive.
2810 CompilerThread* ct = (CompilerThread*)this;
2811 if (ct->env() != NULL) {
2812 ct->env()->metadata_do(f);
2813 }
2814 }
2815 }
2817 // Printing
2818 const char* _get_thread_state_name(JavaThreadState _thread_state) {
2819 switch (_thread_state) {
2820 case _thread_uninitialized: return "_thread_uninitialized";
2821 case _thread_new: return "_thread_new";
2822 case _thread_new_trans: return "_thread_new_trans";
2823 case _thread_in_native: return "_thread_in_native";
2824 case _thread_in_native_trans: return "_thread_in_native_trans";
2825 case _thread_in_vm: return "_thread_in_vm";
2826 case _thread_in_vm_trans: return "_thread_in_vm_trans";
2827 case _thread_in_Java: return "_thread_in_Java";
2828 case _thread_in_Java_trans: return "_thread_in_Java_trans";
2829 case _thread_blocked: return "_thread_blocked";
2830 case _thread_blocked_trans: return "_thread_blocked_trans";
2831 default: return "unknown thread state";
2832 }
2833 }
2835 #ifndef PRODUCT
2836 void JavaThread::print_thread_state_on(outputStream *st) const {
2837 st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state));
2838 };
2839 void JavaThread::print_thread_state() const {
2840 print_thread_state_on(tty);
2841 };
2842 #endif // PRODUCT
2844 // Called by Threads::print() for VM_PrintThreads operation
2845 void JavaThread::print_on(outputStream *st) const {
2846 st->print("\"%s\" ", get_thread_name());
2847 oop thread_oop = threadObj();
2848 if (thread_oop != NULL) {
2849 st->print("#" INT64_FORMAT " ", java_lang_Thread::thread_id(thread_oop));
2850 if (java_lang_Thread::is_daemon(thread_oop)) st->print("daemon ");
2851 st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
2852 }
2853 Thread::print_on(st);
2854 // print guess for valid stack memory region (assume 4K pages); helps lock debugging
2855 st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
2856 if (thread_oop != NULL && JDK_Version::is_gte_jdk15x_version()) {
2857 st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
2858 }
2859 #ifndef PRODUCT
2860 print_thread_state_on(st);
2861 _safepoint_state->print_on(st);
2862 #endif // PRODUCT
2863 }
2865 // Called by fatal error handler. The difference between this and
2866 // JavaThread::print() is that we can't grab lock or allocate memory.
2867 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
2868 st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
2869 oop thread_obj = threadObj();
2870 if (thread_obj != NULL) {
2871 if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
2872 }
2873 st->print(" [");
2874 st->print("%s", _get_thread_state_name(_thread_state));
2875 if (osthread()) {
2876 st->print(", id=%d", osthread()->thread_id());
2877 }
2878 st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
2879 _stack_base - _stack_size, _stack_base);
2880 st->print("]");
2881 return;
2882 }
2884 // Verification
2886 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
2888 void JavaThread::verify() {
2889 // Verify oops in the thread.
2890 oops_do(&VerifyOopClosure::verify_oop, NULL, NULL);
2892 // Verify the stack frames.
2893 frames_do(frame_verify);
2894 }
2896 // CR 6300358 (sub-CR 2137150)
2897 // Most callers of this method assume that it can't return NULL but a
2898 // thread may not have a name whilst it is in the process of attaching to
2899 // the VM - see CR 6412693, and there are places where a JavaThread can be
2900 // seen prior to having it's threadObj set (eg JNI attaching threads and
2901 // if vm exit occurs during initialization). These cases can all be accounted
2902 // for such that this method never returns NULL.
2903 const char* JavaThread::get_thread_name() const {
2904 #ifdef ASSERT
2905 // early safepoints can hit while current thread does not yet have TLS
2906 if (!SafepointSynchronize::is_at_safepoint()) {
2907 Thread *cur = Thread::current();
2908 if (!(cur->is_Java_thread() && cur == this)) {
2909 // Current JavaThreads are allowed to get their own name without
2910 // the Threads_lock.
2911 assert_locked_or_safepoint(Threads_lock);
2912 }
2913 }
2914 #endif // ASSERT
2915 return get_thread_name_string();
2916 }
2918 // Returns a non-NULL representation of this thread's name, or a suitable
2919 // descriptive string if there is no set name
2920 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
2921 const char* name_str;
2922 oop thread_obj = threadObj();
2923 if (thread_obj != NULL) {
2924 typeArrayOop name = java_lang_Thread::name(thread_obj);
2925 if (name != NULL) {
2926 if (buf == NULL) {
2927 name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
2928 }
2929 else {
2930 name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length(), buf, buflen);
2931 }
2932 }
2933 else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
2934 name_str = "<no-name - thread is attaching>";
2935 }
2936 else {
2937 name_str = Thread::name();
2938 }
2939 }
2940 else {
2941 name_str = Thread::name();
2942 }
2943 assert(name_str != NULL, "unexpected NULL thread name");
2944 return name_str;
2945 }
2948 const char* JavaThread::get_threadgroup_name() const {
2949 debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
2950 oop thread_obj = threadObj();
2951 if (thread_obj != NULL) {
2952 oop thread_group = java_lang_Thread::threadGroup(thread_obj);
2953 if (thread_group != NULL) {
2954 typeArrayOop name = java_lang_ThreadGroup::name(thread_group);
2955 // ThreadGroup.name can be null
2956 if (name != NULL) {
2957 const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
2958 return str;
2959 }
2960 }
2961 }
2962 return NULL;
2963 }
2965 const char* JavaThread::get_parent_name() const {
2966 debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
2967 oop thread_obj = threadObj();
2968 if (thread_obj != NULL) {
2969 oop thread_group = java_lang_Thread::threadGroup(thread_obj);
2970 if (thread_group != NULL) {
2971 oop parent = java_lang_ThreadGroup::parent(thread_group);
2972 if (parent != NULL) {
2973 typeArrayOop name = java_lang_ThreadGroup::name(parent);
2974 // ThreadGroup.name can be null
2975 if (name != NULL) {
2976 const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
2977 return str;
2978 }
2979 }
2980 }
2981 }
2982 return NULL;
2983 }
2985 ThreadPriority JavaThread::java_priority() const {
2986 oop thr_oop = threadObj();
2987 if (thr_oop == NULL) return NormPriority; // Bootstrapping
2988 ThreadPriority priority = java_lang_Thread::priority(thr_oop);
2989 assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
2990 return priority;
2991 }
2993 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
2995 assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2996 // Link Java Thread object <-> C++ Thread
2998 // Get the C++ thread object (an oop) from the JNI handle (a jthread)
2999 // and put it into a new Handle. The Handle "thread_oop" can then
3000 // be used to pass the C++ thread object to other methods.
3002 // Set the Java level thread object (jthread) field of the
3003 // new thread (a JavaThread *) to C++ thread object using the
3004 // "thread_oop" handle.
3006 // Set the thread field (a JavaThread *) of the
3007 // oop representing the java_lang_Thread to the new thread (a JavaThread *).
3009 Handle thread_oop(Thread::current(),
3010 JNIHandles::resolve_non_null(jni_thread));
3011 assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
3012 "must be initialized");
3013 set_threadObj(thread_oop());
3014 java_lang_Thread::set_thread(thread_oop(), this);
3016 if (prio == NoPriority) {
3017 prio = java_lang_Thread::priority(thread_oop());
3018 assert(prio != NoPriority, "A valid priority should be present");
3019 }
3021 // Push the Java priority down to the native thread; needs Threads_lock
3022 Thread::set_priority(this, prio);
3024 // Add the new thread to the Threads list and set it in motion.
3025 // We must have threads lock in order to call Threads::add.
3026 // It is crucial that we do not block before the thread is
3027 // added to the Threads list for if a GC happens, then the java_thread oop
3028 // will not be visited by GC.
3029 Threads::add(this);
3030 }
3032 oop JavaThread::current_park_blocker() {
3033 // Support for JSR-166 locks
3034 oop thread_oop = threadObj();
3035 if (thread_oop != NULL &&
3036 JDK_Version::current().supports_thread_park_blocker()) {
3037 return java_lang_Thread::park_blocker(thread_oop);
3038 }
3039 return NULL;
3040 }
3043 void JavaThread::print_stack_on(outputStream* st) {
3044 if (!has_last_Java_frame()) return;
3045 ResourceMark rm;
3046 HandleMark hm;
3048 RegisterMap reg_map(this);
3049 vframe* start_vf = last_java_vframe(®_map);
3050 int count = 0;
3051 for (vframe* f = start_vf; f; f = f->sender() ) {
3052 if (f->is_java_frame()) {
3053 javaVFrame* jvf = javaVFrame::cast(f);
3054 java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
3056 // Print out lock information
3057 if (JavaMonitorsInStackTrace) {
3058 jvf->print_lock_info_on(st, count);
3059 }
3060 } else {
3061 // Ignore non-Java frames
3062 }
3064 // Bail-out case for too deep stacks
3065 count++;
3066 if (MaxJavaStackTraceDepth == count) return;
3067 }
3068 }
3071 // JVMTI PopFrame support
3072 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
3073 assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
3074 if (in_bytes(size_in_bytes) != 0) {
3075 _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
3076 _popframe_preserved_args_size = in_bytes(size_in_bytes);
3077 Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
3078 }
3079 }
3081 void* JavaThread::popframe_preserved_args() {
3082 return _popframe_preserved_args;
3083 }
3085 ByteSize JavaThread::popframe_preserved_args_size() {
3086 return in_ByteSize(_popframe_preserved_args_size);
3087 }
3089 WordSize JavaThread::popframe_preserved_args_size_in_words() {
3090 int sz = in_bytes(popframe_preserved_args_size());
3091 assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
3092 return in_WordSize(sz / wordSize);
3093 }
3095 void JavaThread::popframe_free_preserved_args() {
3096 assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
3097 FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args, mtThread);
3098 _popframe_preserved_args = NULL;
3099 _popframe_preserved_args_size = 0;
3100 }
3102 #ifndef PRODUCT
3104 void JavaThread::trace_frames() {
3105 tty->print_cr("[Describe stack]");
3106 int frame_no = 1;
3107 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
3108 tty->print(" %d. ", frame_no++);
3109 fst.current()->print_value_on(tty,this);
3110 tty->cr();
3111 }
3112 }
3114 class PrintAndVerifyOopClosure: public OopClosure {
3115 protected:
3116 template <class T> inline void do_oop_work(T* p) {
3117 oop obj = oopDesc::load_decode_heap_oop(p);
3118 if (obj == NULL) return;
3119 tty->print(INTPTR_FORMAT ": ", p);
3120 if (obj->is_oop_or_null()) {
3121 if (obj->is_objArray()) {
3122 tty->print_cr("valid objArray: " INTPTR_FORMAT, (oopDesc*) obj);
3123 } else {
3124 obj->print();
3125 }
3126 } else {
3127 tty->print_cr("invalid oop: " INTPTR_FORMAT, (oopDesc*) obj);
3128 }
3129 tty->cr();
3130 }
3131 public:
3132 virtual void do_oop(oop* p) { do_oop_work(p); }
3133 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
3134 };
3137 static void oops_print(frame* f, const RegisterMap *map) {
3138 PrintAndVerifyOopClosure print;
3139 f->print_value();
3140 f->oops_do(&print, NULL, NULL, (RegisterMap*)map);
3141 }
3143 // Print our all the locations that contain oops and whether they are
3144 // valid or not. This useful when trying to find the oldest frame
3145 // where an oop has gone bad since the frame walk is from youngest to
3146 // oldest.
3147 void JavaThread::trace_oops() {
3148 tty->print_cr("[Trace oops]");
3149 frames_do(oops_print);
3150 }
3153 #ifdef ASSERT
3154 // Print or validate the layout of stack frames
3155 void JavaThread::print_frame_layout(int depth, bool validate_only) {
3156 ResourceMark rm;
3157 PRESERVE_EXCEPTION_MARK;
3158 FrameValues values;
3159 int frame_no = 0;
3160 for(StackFrameStream fst(this, false); !fst.is_done(); fst.next()) {
3161 fst.current()->describe(values, ++frame_no);
3162 if (depth == frame_no) break;
3163 }
3164 if (validate_only) {
3165 values.validate();
3166 } else {
3167 tty->print_cr("[Describe stack layout]");
3168 values.print(this);
3169 }
3170 }
3171 #endif
3173 void JavaThread::trace_stack_from(vframe* start_vf) {
3174 ResourceMark rm;
3175 int vframe_no = 1;
3176 for (vframe* f = start_vf; f; f = f->sender() ) {
3177 if (f->is_java_frame()) {
3178 javaVFrame::cast(f)->print_activation(vframe_no++);
3179 } else {
3180 f->print();
3181 }
3182 if (vframe_no > StackPrintLimit) {
3183 tty->print_cr("...<more frames>...");
3184 return;
3185 }
3186 }
3187 }
3190 void JavaThread::trace_stack() {
3191 if (!has_last_Java_frame()) return;
3192 ResourceMark rm;
3193 HandleMark hm;
3194 RegisterMap reg_map(this);
3195 trace_stack_from(last_java_vframe(®_map));
3196 }
3199 #endif // PRODUCT
3202 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
3203 assert(reg_map != NULL, "a map must be given");
3204 frame f = last_frame();
3205 for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender() ) {
3206 if (vf->is_java_frame()) return javaVFrame::cast(vf);
3207 }
3208 return NULL;
3209 }
3212 Klass* JavaThread::security_get_caller_class(int depth) {
3213 vframeStream vfst(this);
3214 vfst.security_get_caller_frame(depth);
3215 if (!vfst.at_end()) {
3216 return vfst.method()->method_holder();
3217 }
3218 return NULL;
3219 }
3221 static void compiler_thread_entry(JavaThread* thread, TRAPS) {
3222 assert(thread->is_Compiler_thread(), "must be compiler thread");
3223 CompileBroker::compiler_thread_loop();
3224 }
3226 // Create a CompilerThread
3227 CompilerThread::CompilerThread(CompileQueue* queue, CompilerCounters* counters)
3228 : JavaThread(&compiler_thread_entry) {
3229 _env = NULL;
3230 _log = NULL;
3231 _task = NULL;
3232 _queue = queue;
3233 _counters = counters;
3234 _buffer_blob = NULL;
3235 _scanned_nmethod = NULL;
3236 _compiler = NULL;
3238 #ifndef PRODUCT
3239 _ideal_graph_printer = NULL;
3240 #endif
3241 }
3243 void CompilerThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
3244 JavaThread::oops_do(f, cld_f, cf);
3245 if (_scanned_nmethod != NULL && cf != NULL) {
3246 // Safepoints can occur when the sweeper is scanning an nmethod so
3247 // process it here to make sure it isn't unloaded in the middle of
3248 // a scan.
3249 cf->do_code_blob(_scanned_nmethod);
3250 }
3251 }
3254 // ======= Threads ========
3256 // The Threads class links together all active threads, and provides
3257 // operations over all threads. It is protected by its own Mutex
3258 // lock, which is also used in other contexts to protect thread
3259 // operations from having the thread being operated on from exiting
3260 // and going away unexpectedly (e.g., safepoint synchronization)
3262 JavaThread* Threads::_thread_list = NULL;
3263 int Threads::_number_of_threads = 0;
3264 int Threads::_number_of_non_daemon_threads = 0;
3265 int Threads::_return_code = 0;
3266 size_t JavaThread::_stack_size_at_create = 0;
3267 #ifdef ASSERT
3268 bool Threads::_vm_complete = false;
3269 #endif
3271 // All JavaThreads
3272 #define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next())
3274 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
3275 void Threads::threads_do(ThreadClosure* tc) {
3276 assert_locked_or_safepoint(Threads_lock);
3277 // ALL_JAVA_THREADS iterates through all JavaThreads
3278 ALL_JAVA_THREADS(p) {
3279 tc->do_thread(p);
3280 }
3281 // Someday we could have a table or list of all non-JavaThreads.
3282 // For now, just manually iterate through them.
3283 tc->do_thread(VMThread::vm_thread());
3284 Universe::heap()->gc_threads_do(tc);
3285 WatcherThread *wt = WatcherThread::watcher_thread();
3286 // Strictly speaking, the following NULL check isn't sufficient to make sure
3287 // the data for WatcherThread is still valid upon being examined. However,
3288 // considering that WatchThread terminates when the VM is on the way to
3289 // exit at safepoint, the chance of the above is extremely small. The right
3290 // way to prevent termination of WatcherThread would be to acquire
3291 // Terminator_lock, but we can't do that without violating the lock rank
3292 // checking in some cases.
3293 if (wt != NULL)
3294 tc->do_thread(wt);
3296 // If CompilerThreads ever become non-JavaThreads, add them here
3297 }
3299 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
3301 extern void JDK_Version_init();
3303 // Check version
3304 if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
3306 // Initialize the output stream module
3307 ostream_init();
3309 // Process java launcher properties.
3310 Arguments::process_sun_java_launcher_properties(args);
3312 // Initialize the os module before using TLS
3313 os::init();
3315 // Initialize system properties.
3316 Arguments::init_system_properties();
3318 // So that JDK version can be used as a discrimintor when parsing arguments
3319 JDK_Version_init();
3321 // Update/Initialize System properties after JDK version number is known
3322 Arguments::init_version_specific_system_properties();
3324 // Parse arguments
3325 jint parse_result = Arguments::parse(args);
3326 if (parse_result != JNI_OK) return parse_result;
3328 os::init_before_ergo();
3330 jint ergo_result = Arguments::apply_ergo();
3331 if (ergo_result != JNI_OK) return ergo_result;
3333 if (PauseAtStartup) {
3334 os::pause();
3335 }
3337 #ifndef USDT2
3338 HS_DTRACE_PROBE(hotspot, vm__init__begin);
3339 #else /* USDT2 */
3340 HOTSPOT_VM_INIT_BEGIN();
3341 #endif /* USDT2 */
3343 // Record VM creation timing statistics
3344 TraceVmCreationTime create_vm_timer;
3345 create_vm_timer.start();
3347 // Timing (must come after argument parsing)
3348 TraceTime timer("Create VM", TraceStartupTime);
3350 // Initialize the os module after parsing the args
3351 jint os_init_2_result = os::init_2();
3352 if (os_init_2_result != JNI_OK) return os_init_2_result;
3354 jint adjust_after_os_result = Arguments::adjust_after_os();
3355 if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
3357 // intialize TLS
3358 ThreadLocalStorage::init();
3360 // Initialize output stream logging
3361 ostream_init_log();
3363 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
3364 // Must be before create_vm_init_agents()
3365 if (Arguments::init_libraries_at_startup()) {
3366 convert_vm_init_libraries_to_agents();
3367 }
3369 // Launch -agentlib/-agentpath and converted -Xrun agents
3370 if (Arguments::init_agents_at_startup()) {
3371 create_vm_init_agents();
3372 }
3374 // Initialize Threads state
3375 _thread_list = NULL;
3376 _number_of_threads = 0;
3377 _number_of_non_daemon_threads = 0;
3379 // Initialize global data structures and create system classes in heap
3380 vm_init_globals();
3382 // Attach the main thread to this os thread
3383 JavaThread* main_thread = new JavaThread();
3384 main_thread->set_thread_state(_thread_in_vm);
3385 // must do this before set_active_handles and initialize_thread_local_storage
3386 // Note: on solaris initialize_thread_local_storage() will (indirectly)
3387 // change the stack size recorded here to one based on the java thread
3388 // stacksize. This adjusted size is what is used to figure the placement
3389 // of the guard pages.
3390 main_thread->record_stack_base_and_size();
3391 main_thread->initialize_thread_local_storage();
3393 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
3395 if (!main_thread->set_as_starting_thread()) {
3396 vm_shutdown_during_initialization(
3397 "Failed necessary internal allocation. Out of swap space");
3398 delete main_thread;
3399 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3400 return JNI_ENOMEM;
3401 }
3403 // Enable guard page *after* os::create_main_thread(), otherwise it would
3404 // crash Linux VM, see notes in os_linux.cpp.
3405 main_thread->create_stack_guard_pages();
3407 // Initialize Java-Level synchronization subsystem
3408 ObjectMonitor::Initialize() ;
3410 // Initialize global modules
3411 jint status = init_globals();
3412 if (status != JNI_OK) {
3413 delete main_thread;
3414 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3415 return status;
3416 }
3418 // Should be done after the heap is fully created
3419 main_thread->cache_global_variables();
3421 HandleMark hm;
3423 { MutexLocker mu(Threads_lock);
3424 Threads::add(main_thread);
3425 }
3427 // Any JVMTI raw monitors entered in onload will transition into
3428 // real raw monitor. VM is setup enough here for raw monitor enter.
3429 JvmtiExport::transition_pending_onload_raw_monitors();
3431 // Create the VMThread
3432 { TraceTime timer("Start VMThread", TraceStartupTime);
3433 VMThread::create();
3434 Thread* vmthread = VMThread::vm_thread();
3436 if (!os::create_thread(vmthread, os::vm_thread))
3437 vm_exit_during_initialization("Cannot create VM thread. Out of system resources.");
3439 // Wait for the VM thread to become ready, and VMThread::run to initialize
3440 // Monitors can have spurious returns, must always check another state flag
3441 {
3442 MutexLocker ml(Notify_lock);
3443 os::start_thread(vmthread);
3444 while (vmthread->active_handles() == NULL) {
3445 Notify_lock->wait();
3446 }
3447 }
3448 }
3450 assert (Universe::is_fully_initialized(), "not initialized");
3451 if (VerifyDuringStartup) {
3452 // Make sure we're starting with a clean slate.
3453 VM_Verify verify_op;
3454 VMThread::execute(&verify_op);
3455 }
3457 EXCEPTION_MARK;
3459 // At this point, the Universe is initialized, but we have not executed
3460 // any byte code. Now is a good time (the only time) to dump out the
3461 // internal state of the JVM for sharing.
3462 if (DumpSharedSpaces) {
3463 MetaspaceShared::preload_and_dump(CHECK_0);
3464 ShouldNotReachHere();
3465 }
3467 // Always call even when there are not JVMTI environments yet, since environments
3468 // may be attached late and JVMTI must track phases of VM execution
3469 JvmtiExport::enter_start_phase();
3471 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
3472 JvmtiExport::post_vm_start();
3474 {
3475 TraceTime timer("Initialize java.lang classes", TraceStartupTime);
3477 if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
3478 create_vm_init_libraries();
3479 }
3481 initialize_class(vmSymbols::java_lang_String(), CHECK_0);
3483 // Initialize java_lang.System (needed before creating the thread)
3484 initialize_class(vmSymbols::java_lang_System(), CHECK_0);
3485 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0);
3486 Handle thread_group = create_initial_thread_group(CHECK_0);
3487 Universe::set_main_thread_group(thread_group());
3488 initialize_class(vmSymbols::java_lang_Thread(), CHECK_0);
3489 oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0);
3490 main_thread->set_threadObj(thread_object);
3491 // Set thread status to running since main thread has
3492 // been started and running.
3493 java_lang_Thread::set_thread_status(thread_object,
3494 java_lang_Thread::RUNNABLE);
3496 // The VM creates & returns objects of this class. Make sure it's initialized.
3497 initialize_class(vmSymbols::java_lang_Class(), CHECK_0);
3499 // The VM preresolves methods to these classes. Make sure that they get initialized
3500 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK_0);
3501 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK_0);
3502 call_initializeSystemClass(CHECK_0);
3504 // get the Java runtime name after java.lang.System is initialized
3505 JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
3506 JDK_Version::set_runtime_version(get_java_runtime_version(THREAD));
3508 // an instance of OutOfMemory exception has been allocated earlier
3509 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK_0);
3510 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK_0);
3511 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK_0);
3512 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK_0);
3513 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK_0);
3514 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK_0);
3515 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK_0);
3516 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK_0);
3517 }
3519 // See : bugid 4211085.
3520 // Background : the static initializer of java.lang.Compiler tries to read
3521 // property"java.compiler" and read & write property "java.vm.info".
3522 // When a security manager is installed through the command line
3523 // option "-Djava.security.manager", the above properties are not
3524 // readable and the static initializer for java.lang.Compiler fails
3525 // resulting in a NoClassDefFoundError. This can happen in any
3526 // user code which calls methods in java.lang.Compiler.
3527 // Hack : the hack is to pre-load and initialize this class, so that only
3528 // system domains are on the stack when the properties are read.
3529 // Currently even the AWT code has calls to methods in java.lang.Compiler.
3530 // On the classic VM, java.lang.Compiler is loaded very early to load the JIT.
3531 // Future Fix : the best fix is to grant everyone permissions to read "java.compiler" and
3532 // read and write"java.vm.info" in the default policy file. See bugid 4211383
3533 // Once that is done, we should remove this hack.
3534 initialize_class(vmSymbols::java_lang_Compiler(), CHECK_0);
3536 // More hackery - the static initializer of java.lang.Compiler adds the string "nojit" to
3537 // the java.vm.info property if no jit gets loaded through java.lang.Compiler (the hotspot
3538 // compiler does not get loaded through java.lang.Compiler). "java -version" with the
3539 // hotspot vm says "nojit" all the time which is confusing. So, we reset it here.
3540 // This should also be taken out as soon as 4211383 gets fixed.
3541 reset_vm_info_property(CHECK_0);
3543 quicken_jni_functions();
3545 // Must be run after init_ft which initializes ft_enabled
3546 if (TRACE_INITIALIZE() != JNI_OK) {
3547 vm_exit_during_initialization("Failed to initialize tracing backend");
3548 }
3550 // Set flag that basic initialization has completed. Used by exceptions and various
3551 // debug stuff, that does not work until all basic classes have been initialized.
3552 set_init_completed();
3554 Metaspace::post_initialize();
3556 #ifndef USDT2
3557 HS_DTRACE_PROBE(hotspot, vm__init__end);
3558 #else /* USDT2 */
3559 HOTSPOT_VM_INIT_END();
3560 #endif /* USDT2 */
3562 // record VM initialization completion time
3563 #if INCLUDE_MANAGEMENT
3564 Management::record_vm_init_completed();
3565 #endif // INCLUDE_MANAGEMENT
3567 // Compute system loader. Note that this has to occur after set_init_completed, since
3568 // valid exceptions may be thrown in the process.
3569 // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
3570 // set_init_completed has just been called, causing exceptions not to be shortcut
3571 // anymore. We call vm_exit_during_initialization directly instead.
3572 SystemDictionary::compute_java_system_loader(THREAD);
3573 if (HAS_PENDING_EXCEPTION) {
3574 vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
3575 }
3577 #if INCLUDE_ALL_GCS
3578 // Support for ConcurrentMarkSweep. This should be cleaned up
3579 // and better encapsulated. The ugly nested if test would go away
3580 // once things are properly refactored. XXX YSR
3581 if (UseConcMarkSweepGC || UseG1GC) {
3582 if (UseConcMarkSweepGC) {
3583 ConcurrentMarkSweepThread::makeSurrogateLockerThread(THREAD);
3584 } else {
3585 ConcurrentMarkThread::makeSurrogateLockerThread(THREAD);
3586 }
3587 if (HAS_PENDING_EXCEPTION) {
3588 vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
3589 }
3590 }
3591 #endif // INCLUDE_ALL_GCS
3593 // Always call even when there are not JVMTI environments yet, since environments
3594 // may be attached late and JVMTI must track phases of VM execution
3595 JvmtiExport::enter_live_phase();
3597 // Signal Dispatcher needs to be started before VMInit event is posted
3598 os::signal_init();
3600 // Start Attach Listener if +StartAttachListener or it can't be started lazily
3601 if (!DisableAttachMechanism) {
3602 AttachListener::vm_start();
3603 if (StartAttachListener || AttachListener::init_at_startup()) {
3604 AttachListener::init();
3605 }
3606 }
3608 // Launch -Xrun agents
3609 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3610 // back-end can launch with -Xdebug -Xrunjdwp.
3611 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3612 create_vm_init_libraries();
3613 }
3615 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3616 JvmtiExport::post_vm_initialized();
3618 if (TRACE_START() != JNI_OK) {
3619 vm_exit_during_initialization("Failed to start tracing backend.");
3620 }
3622 if (CleanChunkPoolAsync) {
3623 Chunk::start_chunk_pool_cleaner_task();
3624 }
3626 // initialize compiler(s)
3627 #if defined(COMPILER1) || defined(COMPILER2) || defined(SHARK)
3628 CompileBroker::compilation_init();
3629 #endif
3631 if (EnableInvokeDynamic) {
3632 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
3633 // It is done after compilers are initialized, because otherwise compilations of
3634 // signature polymorphic MH intrinsics can be missed
3635 // (see SystemDictionary::find_method_handle_intrinsic).
3636 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK_0);
3637 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK_0);
3638 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK_0);
3639 }
3641 #if INCLUDE_MANAGEMENT
3642 Management::initialize(THREAD);
3643 #endif // INCLUDE_MANAGEMENT
3645 if (HAS_PENDING_EXCEPTION) {
3646 // management agent fails to start possibly due to
3647 // configuration problem and is responsible for printing
3648 // stack trace if appropriate. Simply exit VM.
3649 vm_exit(1);
3650 }
3652 if (Arguments::has_profile()) FlatProfiler::engage(main_thread, true);
3653 if (MemProfiling) MemProfiler::engage();
3654 StatSampler::engage();
3655 if (CheckJNICalls) JniPeriodicChecker::engage();
3657 BiasedLocking::init();
3659 #if INCLUDE_RTM_OPT
3660 RTMLockingCounters::init();
3661 #endif
3663 if (JDK_Version::current().post_vm_init_hook_enabled()) {
3664 call_postVMInitHook(THREAD);
3665 // The Java side of PostVMInitHook.run must deal with all
3666 // exceptions and provide means of diagnosis.
3667 if (HAS_PENDING_EXCEPTION) {
3668 CLEAR_PENDING_EXCEPTION;
3669 }
3670 }
3672 {
3673 MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
3674 // Make sure the watcher thread can be started by WatcherThread::start()
3675 // or by dynamic enrollment.
3676 WatcherThread::make_startable();
3677 // Start up the WatcherThread if there are any periodic tasks
3678 // NOTE: All PeriodicTasks should be registered by now. If they
3679 // aren't, late joiners might appear to start slowly (we might
3680 // take a while to process their first tick).
3681 if (PeriodicTask::num_tasks() > 0) {
3682 WatcherThread::start();
3683 }
3684 }
3686 // Give os specific code one last chance to start
3687 os::init_3();
3689 create_vm_timer.end();
3690 #ifdef ASSERT
3691 _vm_complete = true;
3692 #endif
3693 return JNI_OK;
3694 }
3696 // type for the Agent_OnLoad and JVM_OnLoad entry points
3697 extern "C" {
3698 typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
3699 }
3700 // Find a command line agent library and return its entry point for
3701 // -agentlib: -agentpath: -Xrun
3702 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
3703 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, const char *on_load_symbols[], size_t num_symbol_entries) {
3704 OnLoadEntry_t on_load_entry = NULL;
3705 void *library = NULL;
3707 if (!agent->valid()) {
3708 char buffer[JVM_MAXPATHLEN];
3709 char ebuf[1024];
3710 const char *name = agent->name();
3711 const char *msg = "Could not find agent library ";
3713 // First check to see if agent is statically linked into executable
3714 if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) {
3715 library = agent->os_lib();
3716 } else if (agent->is_absolute_path()) {
3717 library = os::dll_load(name, ebuf, sizeof ebuf);
3718 if (library == NULL) {
3719 const char *sub_msg = " in absolute path, with error: ";
3720 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
3721 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
3722 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
3723 // If we can't find the agent, exit.
3724 vm_exit_during_initialization(buf, NULL);
3725 FREE_C_HEAP_ARRAY(char, buf, mtThread);
3726 }
3727 } else {
3728 // Try to load the agent from the standard dll directory
3729 if (os::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
3730 name)) {
3731 library = os::dll_load(buffer, ebuf, sizeof ebuf);
3732 }
3733 if (library == NULL) { // Try the local directory
3734 char ns[1] = {0};
3735 if (os::dll_build_name(buffer, sizeof(buffer), ns, name)) {
3736 library = os::dll_load(buffer, ebuf, sizeof ebuf);
3737 }
3738 if (library == NULL) {
3739 const char *sub_msg = " on the library path, with error: ";
3740 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
3741 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
3742 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
3743 // If we can't find the agent, exit.
3744 vm_exit_during_initialization(buf, NULL);
3745 FREE_C_HEAP_ARRAY(char, buf, mtThread);
3746 }
3747 }
3748 }
3749 agent->set_os_lib(library);
3750 agent->set_valid();
3751 }
3753 // Find the OnLoad function.
3754 on_load_entry =
3755 CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent,
3756 false,
3757 on_load_symbols,
3758 num_symbol_entries));
3759 return on_load_entry;
3760 }
3762 // Find the JVM_OnLoad entry point
3763 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
3764 const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
3765 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
3766 }
3768 // Find the Agent_OnLoad entry point
3769 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
3770 const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
3771 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
3772 }
3774 // For backwards compatibility with -Xrun
3775 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
3776 // treated like -agentpath:
3777 // Must be called before agent libraries are created
3778 void Threads::convert_vm_init_libraries_to_agents() {
3779 AgentLibrary* agent;
3780 AgentLibrary* next;
3782 for (agent = Arguments::libraries(); agent != NULL; agent = next) {
3783 next = agent->next(); // cache the next agent now as this agent may get moved off this list
3784 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
3786 // If there is an JVM_OnLoad function it will get called later,
3787 // otherwise see if there is an Agent_OnLoad
3788 if (on_load_entry == NULL) {
3789 on_load_entry = lookup_agent_on_load(agent);
3790 if (on_load_entry != NULL) {
3791 // switch it to the agent list -- so that Agent_OnLoad will be called,
3792 // JVM_OnLoad won't be attempted and Agent_OnUnload will
3793 Arguments::convert_library_to_agent(agent);
3794 } else {
3795 vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
3796 }
3797 }
3798 }
3799 }
3801 // Create agents for -agentlib: -agentpath: and converted -Xrun
3802 // Invokes Agent_OnLoad
3803 // Called very early -- before JavaThreads exist
3804 void Threads::create_vm_init_agents() {
3805 extern struct JavaVM_ main_vm;
3806 AgentLibrary* agent;
3808 JvmtiExport::enter_onload_phase();
3810 for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
3811 OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent);
3813 if (on_load_entry != NULL) {
3814 // Invoke the Agent_OnLoad function
3815 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
3816 if (err != JNI_OK) {
3817 vm_exit_during_initialization("agent library failed to init", agent->name());
3818 }
3819 } else {
3820 vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
3821 }
3822 }
3823 JvmtiExport::enter_primordial_phase();
3824 }
3826 extern "C" {
3827 typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
3828 }
3830 void Threads::shutdown_vm_agents() {
3831 // Send any Agent_OnUnload notifications
3832 const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
3833 size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols);
3834 extern struct JavaVM_ main_vm;
3835 for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
3837 // Find the Agent_OnUnload function.
3838 Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
3839 os::find_agent_function(agent,
3840 false,
3841 on_unload_symbols,
3842 num_symbol_entries));
3844 // Invoke the Agent_OnUnload function
3845 if (unload_entry != NULL) {
3846 JavaThread* thread = JavaThread::current();
3847 ThreadToNativeFromVM ttn(thread);
3848 HandleMark hm(thread);
3849 (*unload_entry)(&main_vm);
3850 }
3851 }
3852 }
3854 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
3855 // Invokes JVM_OnLoad
3856 void Threads::create_vm_init_libraries() {
3857 extern struct JavaVM_ main_vm;
3858 AgentLibrary* agent;
3860 for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
3861 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
3863 if (on_load_entry != NULL) {
3864 // Invoke the JVM_OnLoad function
3865 JavaThread* thread = JavaThread::current();
3866 ThreadToNativeFromVM ttn(thread);
3867 HandleMark hm(thread);
3868 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
3869 if (err != JNI_OK) {
3870 vm_exit_during_initialization("-Xrun library failed to init", agent->name());
3871 }
3872 } else {
3873 vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
3874 }
3875 }
3876 }
3878 // Last thread running calls java.lang.Shutdown.shutdown()
3879 void JavaThread::invoke_shutdown_hooks() {
3880 HandleMark hm(this);
3882 // We could get here with a pending exception, if so clear it now.
3883 if (this->has_pending_exception()) {
3884 this->clear_pending_exception();
3885 }
3887 EXCEPTION_MARK;
3888 Klass* k =
3889 SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
3890 THREAD);
3891 if (k != NULL) {
3892 // SystemDictionary::resolve_or_null will return null if there was
3893 // an exception. If we cannot load the Shutdown class, just don't
3894 // call Shutdown.shutdown() at all. This will mean the shutdown hooks
3895 // and finalizers (if runFinalizersOnExit is set) won't be run.
3896 // Note that if a shutdown hook was registered or runFinalizersOnExit
3897 // was called, the Shutdown class would have already been loaded
3898 // (Runtime.addShutdownHook and runFinalizersOnExit will load it).
3899 instanceKlassHandle shutdown_klass (THREAD, k);
3900 JavaValue result(T_VOID);
3901 JavaCalls::call_static(&result,
3902 shutdown_klass,
3903 vmSymbols::shutdown_method_name(),
3904 vmSymbols::void_method_signature(),
3905 THREAD);
3906 }
3907 CLEAR_PENDING_EXCEPTION;
3908 }
3910 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
3911 // the program falls off the end of main(). Another VM exit path is through
3912 // vm_exit() when the program calls System.exit() to return a value or when
3913 // there is a serious error in VM. The two shutdown paths are not exactly
3914 // the same, but they share Shutdown.shutdown() at Java level and before_exit()
3915 // and VM_Exit op at VM level.
3916 //
3917 // Shutdown sequence:
3918 // + Shutdown native memory tracking if it is on
3919 // + Wait until we are the last non-daemon thread to execute
3920 // <-- every thing is still working at this moment -->
3921 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
3922 // shutdown hooks, run finalizers if finalization-on-exit
3923 // + Call before_exit(), prepare for VM exit
3924 // > run VM level shutdown hooks (they are registered through JVM_OnExit(),
3925 // currently the only user of this mechanism is File.deleteOnExit())
3926 // > stop flat profiler, StatSampler, watcher thread, CMS threads,
3927 // post thread end and vm death events to JVMTI,
3928 // stop signal thread
3929 // + Call JavaThread::exit(), it will:
3930 // > release JNI handle blocks, remove stack guard pages
3931 // > remove this thread from Threads list
3932 // <-- no more Java code from this thread after this point -->
3933 // + Stop VM thread, it will bring the remaining VM to a safepoint and stop
3934 // the compiler threads at safepoint
3935 // <-- do not use anything that could get blocked by Safepoint -->
3936 // + Disable tracing at JNI/JVM barriers
3937 // + Set _vm_exited flag for threads that are still running native code
3938 // + Delete this thread
3939 // + Call exit_globals()
3940 // > deletes tty
3941 // > deletes PerfMemory resources
3942 // + Return to caller
3944 bool Threads::destroy_vm() {
3945 JavaThread* thread = JavaThread::current();
3947 #ifdef ASSERT
3948 _vm_complete = false;
3949 #endif
3950 // Wait until we are the last non-daemon thread to execute
3951 { MutexLocker nu(Threads_lock);
3952 while (Threads::number_of_non_daemon_threads() > 1 )
3953 // This wait should make safepoint checks, wait without a timeout,
3954 // and wait as a suspend-equivalent condition.
3955 //
3956 // Note: If the FlatProfiler is running and this thread is waiting
3957 // for another non-daemon thread to finish, then the FlatProfiler
3958 // is waiting for the external suspend request on this thread to
3959 // complete. wait_for_ext_suspend_completion() will eventually
3960 // timeout, but that takes time. Making this wait a suspend-
3961 // equivalent condition solves that timeout problem.
3962 //
3963 Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
3964 Mutex::_as_suspend_equivalent_flag);
3965 }
3967 // Hang forever on exit if we are reporting an error.
3968 if (ShowMessageBoxOnError && is_error_reported()) {
3969 os::infinite_sleep();
3970 }
3971 os::wait_for_keypress_at_exit();
3973 if (JDK_Version::is_jdk12x_version()) {
3974 // We are the last thread running, so check if finalizers should be run.
3975 // For 1.3 or later this is done in thread->invoke_shutdown_hooks()
3976 HandleMark rm(thread);
3977 Universe::run_finalizers_on_exit();
3978 } else {
3979 // run Java level shutdown hooks
3980 thread->invoke_shutdown_hooks();
3981 }
3983 before_exit(thread);
3985 thread->exit(true);
3987 // Stop VM thread.
3988 {
3989 // 4945125 The vm thread comes to a safepoint during exit.
3990 // GC vm_operations can get caught at the safepoint, and the
3991 // heap is unparseable if they are caught. Grab the Heap_lock
3992 // to prevent this. The GC vm_operations will not be able to
3993 // queue until after the vm thread is dead. After this point,
3994 // we'll never emerge out of the safepoint before the VM exits.
3996 MutexLocker ml(Heap_lock);
3998 VMThread::wait_for_vm_thread_exit();
3999 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
4000 VMThread::destroy();
4001 }
4003 // clean up ideal graph printers
4004 #if defined(COMPILER2) && !defined(PRODUCT)
4005 IdealGraphPrinter::clean_up();
4006 #endif
4008 // Now, all Java threads are gone except daemon threads. Daemon threads
4009 // running Java code or in VM are stopped by the Safepoint. However,
4010 // daemon threads executing native code are still running. But they
4011 // will be stopped at native=>Java/VM barriers. Note that we can't
4012 // simply kill or suspend them, as it is inherently deadlock-prone.
4014 #ifndef PRODUCT
4015 // disable function tracing at JNI/JVM barriers
4016 TraceJNICalls = false;
4017 TraceJVMCalls = false;
4018 TraceRuntimeCalls = false;
4019 #endif
4021 VM_Exit::set_vm_exited();
4023 notify_vm_shutdown();
4025 delete thread;
4027 // exit_globals() will delete tty
4028 exit_globals();
4030 return true;
4031 }
4034 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
4035 if (version == JNI_VERSION_1_1) return JNI_TRUE;
4036 return is_supported_jni_version(version);
4037 }
4040 jboolean Threads::is_supported_jni_version(jint version) {
4041 if (version == JNI_VERSION_1_2) return JNI_TRUE;
4042 if (version == JNI_VERSION_1_4) return JNI_TRUE;
4043 if (version == JNI_VERSION_1_6) return JNI_TRUE;
4044 if (version == JNI_VERSION_1_8) return JNI_TRUE;
4045 return JNI_FALSE;
4046 }
4049 void Threads::add(JavaThread* p, bool force_daemon) {
4050 // The threads lock must be owned at this point
4051 assert_locked_or_safepoint(Threads_lock);
4053 // See the comment for this method in thread.hpp for its purpose and
4054 // why it is called here.
4055 p->initialize_queues();
4056 p->set_next(_thread_list);
4057 _thread_list = p;
4058 _number_of_threads++;
4059 oop threadObj = p->threadObj();
4060 bool daemon = true;
4061 // Bootstrapping problem: threadObj can be null for initial
4062 // JavaThread (or for threads attached via JNI)
4063 if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) {
4064 _number_of_non_daemon_threads++;
4065 daemon = false;
4066 }
4068 ThreadService::add_thread(p, daemon);
4070 // Possible GC point.
4071 Events::log(p, "Thread added: " INTPTR_FORMAT, p);
4072 }
4074 void Threads::remove(JavaThread* p) {
4075 // Extra scope needed for Thread_lock, so we can check
4076 // that we do not remove thread without safepoint code notice
4077 { MutexLocker ml(Threads_lock);
4079 assert(includes(p), "p must be present");
4081 JavaThread* current = _thread_list;
4082 JavaThread* prev = NULL;
4084 while (current != p) {
4085 prev = current;
4086 current = current->next();
4087 }
4089 if (prev) {
4090 prev->set_next(current->next());
4091 } else {
4092 _thread_list = p->next();
4093 }
4094 _number_of_threads--;
4095 oop threadObj = p->threadObj();
4096 bool daemon = true;
4097 if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
4098 _number_of_non_daemon_threads--;
4099 daemon = false;
4101 // Only one thread left, do a notify on the Threads_lock so a thread waiting
4102 // on destroy_vm will wake up.
4103 if (number_of_non_daemon_threads() == 1)
4104 Threads_lock->notify_all();
4105 }
4106 ThreadService::remove_thread(p, daemon);
4108 // Make sure that safepoint code disregard this thread. This is needed since
4109 // the thread might mess around with locks after this point. This can cause it
4110 // to do callbacks into the safepoint code. However, the safepoint code is not aware
4111 // of this thread since it is removed from the queue.
4112 p->set_terminated_value();
4113 } // unlock Threads_lock
4115 // Since Events::log uses a lock, we grab it outside the Threads_lock
4116 Events::log(p, "Thread exited: " INTPTR_FORMAT, p);
4117 }
4119 // Threads_lock must be held when this is called (or must be called during a safepoint)
4120 bool Threads::includes(JavaThread* p) {
4121 assert(Threads_lock->is_locked(), "sanity check");
4122 ALL_JAVA_THREADS(q) {
4123 if (q == p ) {
4124 return true;
4125 }
4126 }
4127 return false;
4128 }
4130 // Operations on the Threads list for GC. These are not explicitly locked,
4131 // but the garbage collector must provide a safe context for them to run.
4132 // In particular, these things should never be called when the Threads_lock
4133 // is held by some other thread. (Note: the Safepoint abstraction also
4134 // uses the Threads_lock to gurantee this property. It also makes sure that
4135 // all threads gets blocked when exiting or starting).
4137 void Threads::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
4138 ALL_JAVA_THREADS(p) {
4139 p->oops_do(f, cld_f, cf);
4140 }
4141 VMThread::vm_thread()->oops_do(f, cld_f, cf);
4142 }
4144 void Threads::possibly_parallel_oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
4145 // Introduce a mechanism allowing parallel threads to claim threads as
4146 // root groups. Overhead should be small enough to use all the time,
4147 // even in sequential code.
4148 SharedHeap* sh = SharedHeap::heap();
4149 // Cannot yet substitute active_workers for n_par_threads
4150 // because of G1CollectedHeap::verify() use of
4151 // SharedHeap::process_roots(). n_par_threads == 0 will
4152 // turn off parallelism in process_roots while active_workers
4153 // is being used for parallelism elsewhere.
4154 bool is_par = sh->n_par_threads() > 0;
4155 assert(!is_par ||
4156 (SharedHeap::heap()->n_par_threads() ==
4157 SharedHeap::heap()->workers()->active_workers()), "Mismatch");
4158 int cp = SharedHeap::heap()->strong_roots_parity();
4159 ALL_JAVA_THREADS(p) {
4160 if (p->claim_oops_do(is_par, cp)) {
4161 p->oops_do(f, cld_f, cf);
4162 }
4163 }
4164 VMThread* vmt = VMThread::vm_thread();
4165 if (vmt->claim_oops_do(is_par, cp)) {
4166 vmt->oops_do(f, cld_f, cf);
4167 }
4168 }
4170 #if INCLUDE_ALL_GCS
4171 // Used by ParallelScavenge
4172 void Threads::create_thread_roots_tasks(GCTaskQueue* q) {
4173 ALL_JAVA_THREADS(p) {
4174 q->enqueue(new ThreadRootsTask(p));
4175 }
4176 q->enqueue(new ThreadRootsTask(VMThread::vm_thread()));
4177 }
4179 // Used by Parallel Old
4180 void Threads::create_thread_roots_marking_tasks(GCTaskQueue* q) {
4181 ALL_JAVA_THREADS(p) {
4182 q->enqueue(new ThreadRootsMarkingTask(p));
4183 }
4184 q->enqueue(new ThreadRootsMarkingTask(VMThread::vm_thread()));
4185 }
4186 #endif // INCLUDE_ALL_GCS
4188 void Threads::nmethods_do(CodeBlobClosure* cf) {
4189 ALL_JAVA_THREADS(p) {
4190 p->nmethods_do(cf);
4191 }
4192 VMThread::vm_thread()->nmethods_do(cf);
4193 }
4195 void Threads::metadata_do(void f(Metadata*)) {
4196 ALL_JAVA_THREADS(p) {
4197 p->metadata_do(f);
4198 }
4199 }
4201 void Threads::gc_epilogue() {
4202 ALL_JAVA_THREADS(p) {
4203 p->gc_epilogue();
4204 }
4205 }
4207 void Threads::gc_prologue() {
4208 ALL_JAVA_THREADS(p) {
4209 p->gc_prologue();
4210 }
4211 }
4213 void Threads::deoptimized_wrt_marked_nmethods() {
4214 ALL_JAVA_THREADS(p) {
4215 p->deoptimized_wrt_marked_nmethods();
4216 }
4217 }
4220 // Get count Java threads that are waiting to enter the specified monitor.
4221 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
4222 address monitor, bool doLock) {
4223 assert(doLock || SafepointSynchronize::is_at_safepoint(),
4224 "must grab Threads_lock or be at safepoint");
4225 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
4227 int i = 0;
4228 {
4229 MutexLockerEx ml(doLock ? Threads_lock : NULL);
4230 ALL_JAVA_THREADS(p) {
4231 if (p->is_Compiler_thread()) continue;
4233 address pending = (address)p->current_pending_monitor();
4234 if (pending == monitor) { // found a match
4235 if (i < count) result->append(p); // save the first count matches
4236 i++;
4237 }
4238 }
4239 }
4240 return result;
4241 }
4244 JavaThread *Threads::owning_thread_from_monitor_owner(address owner, bool doLock) {
4245 assert(doLock ||
4246 Threads_lock->owned_by_self() ||
4247 SafepointSynchronize::is_at_safepoint(),
4248 "must grab Threads_lock or be at safepoint");
4250 // NULL owner means not locked so we can skip the search
4251 if (owner == NULL) return NULL;
4253 {
4254 MutexLockerEx ml(doLock ? Threads_lock : NULL);
4255 ALL_JAVA_THREADS(p) {
4256 // first, see if owner is the address of a Java thread
4257 if (owner == (address)p) return p;
4258 }
4259 }
4260 // Cannot assert on lack of success here since this function may be
4261 // used by code that is trying to report useful problem information
4262 // like deadlock detection.
4263 if (UseHeavyMonitors) return NULL;
4265 //
4266 // If we didn't find a matching Java thread and we didn't force use of
4267 // heavyweight monitors, then the owner is the stack address of the
4268 // Lock Word in the owning Java thread's stack.
4269 //
4270 JavaThread* the_owner = NULL;
4271 {
4272 MutexLockerEx ml(doLock ? Threads_lock : NULL);
4273 ALL_JAVA_THREADS(q) {
4274 if (q->is_lock_owned(owner)) {
4275 the_owner = q;
4276 break;
4277 }
4278 }
4279 }
4280 // cannot assert on lack of success here; see above comment
4281 return the_owner;
4282 }
4284 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
4285 void Threads::print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks) {
4286 char buf[32];
4287 st->print_cr("%s", os::local_time_string(buf, sizeof(buf)));
4289 st->print_cr("Full thread dump %s (%s %s):",
4290 Abstract_VM_Version::vm_name(),
4291 Abstract_VM_Version::vm_release(),
4292 Abstract_VM_Version::vm_info_string()
4293 );
4294 st->cr();
4296 #if INCLUDE_ALL_GCS
4297 // Dump concurrent locks
4298 ConcurrentLocksDump concurrent_locks;
4299 if (print_concurrent_locks) {
4300 concurrent_locks.dump_at_safepoint();
4301 }
4302 #endif // INCLUDE_ALL_GCS
4304 ALL_JAVA_THREADS(p) {
4305 ResourceMark rm;
4306 p->print_on(st);
4307 if (print_stacks) {
4308 if (internal_format) {
4309 p->trace_stack();
4310 } else {
4311 p->print_stack_on(st);
4312 }
4313 }
4314 st->cr();
4315 #if INCLUDE_ALL_GCS
4316 if (print_concurrent_locks) {
4317 concurrent_locks.print_locks_on(p, st);
4318 }
4319 #endif // INCLUDE_ALL_GCS
4320 }
4322 VMThread::vm_thread()->print_on(st);
4323 st->cr();
4324 Universe::heap()->print_gc_threads_on(st);
4325 WatcherThread* wt = WatcherThread::watcher_thread();
4326 if (wt != NULL) {
4327 wt->print_on(st);
4328 st->cr();
4329 }
4330 CompileBroker::print_compiler_threads_on(st);
4331 st->flush();
4332 }
4334 // Threads::print_on_error() is called by fatal error handler. It's possible
4335 // that VM is not at safepoint and/or current thread is inside signal handler.
4336 // Don't print stack trace, as the stack may not be walkable. Don't allocate
4337 // memory (even in resource area), it might deadlock the error handler.
4338 void Threads::print_on_error(outputStream* st, Thread* current, char* buf, int buflen) {
4339 bool found_current = false;
4340 st->print_cr("Java Threads: ( => current thread )");
4341 ALL_JAVA_THREADS(thread) {
4342 bool is_current = (current == thread);
4343 found_current = found_current || is_current;
4345 st->print("%s", is_current ? "=>" : " ");
4347 st->print(PTR_FORMAT, thread);
4348 st->print(" ");
4349 thread->print_on_error(st, buf, buflen);
4350 st->cr();
4351 }
4352 st->cr();
4354 st->print_cr("Other Threads:");
4355 if (VMThread::vm_thread()) {
4356 bool is_current = (current == VMThread::vm_thread());
4357 found_current = found_current || is_current;
4358 st->print("%s", current == VMThread::vm_thread() ? "=>" : " ");
4360 st->print(PTR_FORMAT, VMThread::vm_thread());
4361 st->print(" ");
4362 VMThread::vm_thread()->print_on_error(st, buf, buflen);
4363 st->cr();
4364 }
4365 WatcherThread* wt = WatcherThread::watcher_thread();
4366 if (wt != NULL) {
4367 bool is_current = (current == wt);
4368 found_current = found_current || is_current;
4369 st->print("%s", is_current ? "=>" : " ");
4371 st->print(PTR_FORMAT, wt);
4372 st->print(" ");
4373 wt->print_on_error(st, buf, buflen);
4374 st->cr();
4375 }
4376 if (!found_current) {
4377 st->cr();
4378 st->print("=>" PTR_FORMAT " (exited) ", current);
4379 current->print_on_error(st, buf, buflen);
4380 st->cr();
4381 }
4382 }
4384 // Internal SpinLock and Mutex
4385 // Based on ParkEvent
4387 // Ad-hoc mutual exclusion primitives: SpinLock and Mux
4388 //
4389 // We employ SpinLocks _only for low-contention, fixed-length
4390 // short-duration critical sections where we're concerned
4391 // about native mutex_t or HotSpot Mutex:: latency.
4392 // The mux construct provides a spin-then-block mutual exclusion
4393 // mechanism.
4394 //
4395 // Testing has shown that contention on the ListLock guarding gFreeList
4396 // is common. If we implement ListLock as a simple SpinLock it's common
4397 // for the JVM to devolve to yielding with little progress. This is true
4398 // despite the fact that the critical sections protected by ListLock are
4399 // extremely short.
4400 //
4401 // TODO-FIXME: ListLock should be of type SpinLock.
4402 // We should make this a 1st-class type, integrated into the lock
4403 // hierarchy as leaf-locks. Critically, the SpinLock structure
4404 // should have sufficient padding to avoid false-sharing and excessive
4405 // cache-coherency traffic.
4408 typedef volatile int SpinLockT ;
4410 void Thread::SpinAcquire (volatile int * adr, const char * LockName) {
4411 if (Atomic::cmpxchg (1, adr, 0) == 0) {
4412 return ; // normal fast-path return
4413 }
4415 // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
4416 TEVENT (SpinAcquire - ctx) ;
4417 int ctr = 0 ;
4418 int Yields = 0 ;
4419 for (;;) {
4420 while (*adr != 0) {
4421 ++ctr ;
4422 if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
4423 if (Yields > 5) {
4424 os::naked_short_sleep(1);
4425 } else {
4426 os::NakedYield() ;
4427 ++Yields ;
4428 }
4429 } else {
4430 SpinPause() ;
4431 }
4432 }
4433 if (Atomic::cmpxchg (1, adr, 0) == 0) return ;
4434 }
4435 }
4437 void Thread::SpinRelease (volatile int * adr) {
4438 assert (*adr != 0, "invariant") ;
4439 OrderAccess::fence() ; // guarantee at least release consistency.
4440 // Roach-motel semantics.
4441 // It's safe if subsequent LDs and STs float "up" into the critical section,
4442 // but prior LDs and STs within the critical section can't be allowed
4443 // to reorder or float past the ST that releases the lock.
4444 *adr = 0 ;
4445 }
4447 // muxAcquire and muxRelease:
4448 //
4449 // * muxAcquire and muxRelease support a single-word lock-word construct.
4450 // The LSB of the word is set IFF the lock is held.
4451 // The remainder of the word points to the head of a singly-linked list
4452 // of threads blocked on the lock.
4453 //
4454 // * The current implementation of muxAcquire-muxRelease uses its own
4455 // dedicated Thread._MuxEvent instance. If we're interested in
4456 // minimizing the peak number of extant ParkEvent instances then
4457 // we could eliminate _MuxEvent and "borrow" _ParkEvent as long
4458 // as certain invariants were satisfied. Specifically, care would need
4459 // to be taken with regards to consuming unpark() "permits".
4460 // A safe rule of thumb is that a thread would never call muxAcquire()
4461 // if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently
4462 // park(). Otherwise the _ParkEvent park() operation in muxAcquire() could
4463 // consume an unpark() permit intended for monitorenter, for instance.
4464 // One way around this would be to widen the restricted-range semaphore
4465 // implemented in park(). Another alternative would be to provide
4466 // multiple instances of the PlatformEvent() for each thread. One
4467 // instance would be dedicated to muxAcquire-muxRelease, for instance.
4468 //
4469 // * Usage:
4470 // -- Only as leaf locks
4471 // -- for short-term locking only as muxAcquire does not perform
4472 // thread state transitions.
4473 //
4474 // Alternatives:
4475 // * We could implement muxAcquire and muxRelease with MCS or CLH locks
4476 // but with parking or spin-then-park instead of pure spinning.
4477 // * Use Taura-Oyama-Yonenzawa locks.
4478 // * It's possible to construct a 1-0 lock if we encode the lockword as
4479 // (List,LockByte). Acquire will CAS the full lockword while Release
4480 // will STB 0 into the LockByte. The 1-0 scheme admits stranding, so
4481 // acquiring threads use timers (ParkTimed) to detect and recover from
4482 // the stranding window. Thread/Node structures must be aligned on 256-byte
4483 // boundaries by using placement-new.
4484 // * Augment MCS with advisory back-link fields maintained with CAS().
4485 // Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner.
4486 // The validity of the backlinks must be ratified before we trust the value.
4487 // If the backlinks are invalid the exiting thread must back-track through the
4488 // the forward links, which are always trustworthy.
4489 // * Add a successor indication. The LockWord is currently encoded as
4490 // (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable
4491 // to provide the usual futile-wakeup optimization.
4492 // See RTStt for details.
4493 // * Consider schedctl.sc_nopreempt to cover the critical section.
4494 //
4497 typedef volatile intptr_t MutexT ; // Mux Lock-word
4498 enum MuxBits { LOCKBIT = 1 } ;
4500 void Thread::muxAcquire (volatile intptr_t * Lock, const char * LockName) {
4501 intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ;
4502 if (w == 0) return ;
4503 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4504 return ;
4505 }
4507 TEVENT (muxAcquire - Contention) ;
4508 ParkEvent * const Self = Thread::current()->_MuxEvent ;
4509 assert ((intptr_t(Self) & LOCKBIT) == 0, "invariant") ;
4510 for (;;) {
4511 int its = (os::is_MP() ? 100 : 0) + 1 ;
4513 // Optional spin phase: spin-then-park strategy
4514 while (--its >= 0) {
4515 w = *Lock ;
4516 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4517 return ;
4518 }
4519 }
4521 Self->reset() ;
4522 Self->OnList = intptr_t(Lock) ;
4523 // The following fence() isn't _strictly necessary as the subsequent
4524 // CAS() both serializes execution and ratifies the fetched *Lock value.
4525 OrderAccess::fence();
4526 for (;;) {
4527 w = *Lock ;
4528 if ((w & LOCKBIT) == 0) {
4529 if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4530 Self->OnList = 0 ; // hygiene - allows stronger asserts
4531 return ;
4532 }
4533 continue ; // Interference -- *Lock changed -- Just retry
4534 }
4535 assert (w & LOCKBIT, "invariant") ;
4536 Self->ListNext = (ParkEvent *) (w & ~LOCKBIT );
4537 if (Atomic::cmpxchg_ptr (intptr_t(Self)|LOCKBIT, Lock, w) == w) break ;
4538 }
4540 while (Self->OnList != 0) {
4541 Self->park() ;
4542 }
4543 }
4544 }
4546 void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) {
4547 intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ;
4548 if (w == 0) return ;
4549 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4550 return ;
4551 }
4553 TEVENT (muxAcquire - Contention) ;
4554 ParkEvent * ReleaseAfter = NULL ;
4555 if (ev == NULL) {
4556 ev = ReleaseAfter = ParkEvent::Allocate (NULL) ;
4557 }
4558 assert ((intptr_t(ev) & LOCKBIT) == 0, "invariant") ;
4559 for (;;) {
4560 guarantee (ev->OnList == 0, "invariant") ;
4561 int its = (os::is_MP() ? 100 : 0) + 1 ;
4563 // Optional spin phase: spin-then-park strategy
4564 while (--its >= 0) {
4565 w = *Lock ;
4566 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4567 if (ReleaseAfter != NULL) {
4568 ParkEvent::Release (ReleaseAfter) ;
4569 }
4570 return ;
4571 }
4572 }
4574 ev->reset() ;
4575 ev->OnList = intptr_t(Lock) ;
4576 // The following fence() isn't _strictly necessary as the subsequent
4577 // CAS() both serializes execution and ratifies the fetched *Lock value.
4578 OrderAccess::fence();
4579 for (;;) {
4580 w = *Lock ;
4581 if ((w & LOCKBIT) == 0) {
4582 if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4583 ev->OnList = 0 ;
4584 // We call ::Release while holding the outer lock, thus
4585 // artificially lengthening the critical section.
4586 // Consider deferring the ::Release() until the subsequent unlock(),
4587 // after we've dropped the outer lock.
4588 if (ReleaseAfter != NULL) {
4589 ParkEvent::Release (ReleaseAfter) ;
4590 }
4591 return ;
4592 }
4593 continue ; // Interference -- *Lock changed -- Just retry
4594 }
4595 assert (w & LOCKBIT, "invariant") ;
4596 ev->ListNext = (ParkEvent *) (w & ~LOCKBIT );
4597 if (Atomic::cmpxchg_ptr (intptr_t(ev)|LOCKBIT, Lock, w) == w) break ;
4598 }
4600 while (ev->OnList != 0) {
4601 ev->park() ;
4602 }
4603 }
4604 }
4606 // Release() must extract a successor from the list and then wake that thread.
4607 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme
4608 // similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based
4609 // Release() would :
4610 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list.
4611 // (B) Extract a successor from the private list "in-hand"
4612 // (C) attempt to CAS() the residual back into *Lock over null.
4613 // If there were any newly arrived threads and the CAS() would fail.
4614 // In that case Release() would detach the RATs, re-merge the list in-hand
4615 // with the RATs and repeat as needed. Alternately, Release() might
4616 // detach and extract a successor, but then pass the residual list to the wakee.
4617 // The wakee would be responsible for reattaching and remerging before it
4618 // competed for the lock.
4619 //
4620 // Both "pop" and DMR are immune from ABA corruption -- there can be
4621 // multiple concurrent pushers, but only one popper or detacher.
4622 // This implementation pops from the head of the list. This is unfair,
4623 // but tends to provide excellent throughput as hot threads remain hot.
4624 // (We wake recently run threads first).
4626 void Thread::muxRelease (volatile intptr_t * Lock) {
4627 for (;;) {
4628 const intptr_t w = Atomic::cmpxchg_ptr (0, Lock, LOCKBIT) ;
4629 assert (w & LOCKBIT, "invariant") ;
4630 if (w == LOCKBIT) return ;
4631 ParkEvent * List = (ParkEvent *) (w & ~LOCKBIT) ;
4632 assert (List != NULL, "invariant") ;
4633 assert (List->OnList == intptr_t(Lock), "invariant") ;
4634 ParkEvent * nxt = List->ListNext ;
4636 // The following CAS() releases the lock and pops the head element.
4637 if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) {
4638 continue ;
4639 }
4640 List->OnList = 0 ;
4641 OrderAccess::fence() ;
4642 List->unpark () ;
4643 return ;
4644 }
4645 }
4648 void Threads::verify() {
4649 ALL_JAVA_THREADS(p) {
4650 p->verify();
4651 }
4652 VMThread* thread = VMThread::vm_thread();
4653 if (thread != NULL) thread->verify();
4654 }