hotspot/src/share/vm/runtime/thread.cpp
changeset 26684 d1221849ea3d
parent 26683 a02753d5a0b2
child 26834 41332d860d6a
equal deleted inserted replaced
26683:a02753d5a0b2 26684:d1221849ea3d
   107 
   107 
   108 #ifdef DTRACE_ENABLED
   108 #ifdef DTRACE_ENABLED
   109 
   109 
   110 // Only bother with this argument setup if dtrace is available
   110 // Only bother with this argument setup if dtrace is available
   111 
   111 
   112 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
   112   #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
   113 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
   113   #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
   114 
   114 
   115 #define DTRACE_THREAD_PROBE(probe, javathread)                             \
   115   #define DTRACE_THREAD_PROBE(probe, javathread)                           \
   116   {                                                                        \
   116     {                                                                      \
   117     ResourceMark rm(this);                                                 \
   117       ResourceMark rm(this);                                               \
   118     int len = 0;                                                           \
   118       int len = 0;                                                         \
   119     const char* name = (javathread)->get_thread_name();                    \
   119       const char* name = (javathread)->get_thread_name();                  \
   120     len = strlen(name);                                                    \
   120       len = strlen(name);                                                  \
   121     HOTSPOT_THREAD_PROBE_##probe(  /* probe = start, stop */               \
   121       HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */               \
   122       (char *) name, len,                                                           \
   122         (char *) name, len,                                                \
   123       java_lang_Thread::thread_id((javathread)->threadObj()),              \
   123         java_lang_Thread::thread_id((javathread)->threadObj()),            \
   124       (uintptr_t) (javathread)->osthread()->thread_id(),                               \
   124         (uintptr_t) (javathread)->osthread()->thread_id(),                 \
   125       java_lang_Thread::is_daemon((javathread)->threadObj()));             \
   125         java_lang_Thread::is_daemon((javathread)->threadObj()));           \
   126   }
   126     }
   127 
   127 
   128 #else //  ndef DTRACE_ENABLED
   128 #else //  ndef DTRACE_ENABLED
   129 
   129 
   130 #define DTRACE_THREAD_PROBE(probe, javathread)
   130   #define DTRACE_THREAD_PROBE(probe, javathread)
   131 
   131 
   132 #endif // ndef DTRACE_ENABLED
   132 #endif // ndef DTRACE_ENABLED
   133 
   133 
   134 
   134 
   135 // Class hierarchy
   135 // Class hierarchy
   152     void* aligned_addr     = (void*) align_size_up((intptr_t) real_malloc_addr, alignment);
   152     void* aligned_addr     = (void*) align_size_up((intptr_t) real_malloc_addr, alignment);
   153     assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
   153     assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
   154            ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
   154            ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
   155            "JavaThread alignment code overflowed allocated storage");
   155            "JavaThread alignment code overflowed allocated storage");
   156     if (TraceBiasedLocking) {
   156     if (TraceBiasedLocking) {
   157       if (aligned_addr != real_malloc_addr)
   157       if (aligned_addr != real_malloc_addr) {
   158         tty->print_cr("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
   158         tty->print_cr("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
   159                       real_malloc_addr, aligned_addr);
   159                       real_malloc_addr, aligned_addr);
       
   160       }
   160     }
   161     }
   161     ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
   162     ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
   162     return aligned_addr;
   163     return aligned_addr;
   163   } else {
   164   } else {
   164     return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
   165     return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
   262     assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
   263     assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
   263     assert(this == _real_malloc_address ||
   264     assert(this == _real_malloc_address ||
   264            this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
   265            this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
   265            "bug in forced alignment of thread objects");
   266            "bug in forced alignment of thread objects");
   266   }
   267   }
   267 #endif /* ASSERT */
   268 #endif // ASSERT
   268 }
   269 }
   269 
   270 
   270 void Thread::initialize_thread_local_storage() {
   271 void Thread::initialize_thread_local_storage() {
   271   // Note: Make sure this method only calls
   272   // Note: Make sure this method only calls
   272   // non-blocking operations. Otherwise, it might not work
   273   // non-blocking operations. Otherwise, it might not work
   443   VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable);
   444   VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable);
   444   VMThread::execute(vm_stop);
   445   VMThread::execute(vm_stop);
   445 }
   446 }
   446 
   447 
   447 
   448 
   448 //
       
   449 // Check if an external suspend request has completed (or has been
   449 // Check if an external suspend request has completed (or has been
   450 // cancelled). Returns true if the thread is externally suspended and
   450 // cancelled). Returns true if the thread is externally suspended and
   451 // false otherwise.
   451 // false otherwise.
   452 //
   452 //
   453 // The bits parameter returns information about the code path through
   453 // The bits parameter returns information about the code path through
   468 // 0x00020000 - suspend request cancelled before loop (return false)
   468 // 0x00020000 - suspend request cancelled before loop (return false)
   469 // 0x00040000 - thread suspended before loop (return true)
   469 // 0x00040000 - thread suspended before loop (return true)
   470 // 0x00080000 - suspend request cancelled in loop (return false)
   470 // 0x00080000 - suspend request cancelled in loop (return false)
   471 // 0x00100000 - thread suspended in loop (return true)
   471 // 0x00100000 - thread suspended in loop (return true)
   472 // 0x00200000 - suspend not completed during retry loop (return false)
   472 // 0x00200000 - suspend not completed during retry loop (return false)
   473 //
       
   474 
   473 
   475 // Helper class for tracing suspend wait debug bits.
   474 // Helper class for tracing suspend wait debug bits.
   476 //
   475 //
   477 // 0x00000100 indicates that the target thread exited before it could
   476 // 0x00000100 indicates that the target thread exited before it could
   478 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
   477 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
   526   }
   525   }
   527 };
   526 };
   528 #undef DEBUG_FALSE_BITS
   527 #undef DEBUG_FALSE_BITS
   529 
   528 
   530 
   529 
   531 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits) {
   530 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay,
       
   531                                           uint32_t *bits) {
   532   TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
   532   TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
   533 
   533 
   534   bool did_trans_retry = false;  // only do thread_in_native_trans retry once
   534   bool did_trans_retry = false;  // only do thread_in_native_trans retry once
   535   bool do_trans_retry;           // flag to force the retry
   535   bool do_trans_retry;           // flag to force the retry
   536 
   536 
   647 
   647 
   648   *bits |= 0x00000010;
   648   *bits |= 0x00000010;
   649   return false;
   649   return false;
   650 }
   650 }
   651 
   651 
   652 //
       
   653 // Wait for an external suspend request to complete (or be cancelled).
   652 // Wait for an external suspend request to complete (or be cancelled).
   654 // Returns true if the thread is externally suspended and false otherwise.
   653 // Returns true if the thread is externally suspended and false otherwise.
   655 //
   654 //
   656 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
   655 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
   657                                                  uint32_t *bits) {
   656                                                  uint32_t *bits) {
   735   *bits |= 0x00200000;
   734   *bits |= 0x00200000;
   736   return false;
   735   return false;
   737 }
   736 }
   738 
   737 
   739 #ifndef PRODUCT
   738 #ifndef PRODUCT
   740 void JavaThread::record_jump(address target, address instr, const char* file, int line) {
   739 void JavaThread::record_jump(address target, address instr, const char* file,
       
   740                              int line) {
   741 
   741 
   742   // This should not need to be atomic as the only way for simultaneous
   742   // This should not need to be atomic as the only way for simultaneous
   743   // updates is via interrupts. Even then this should be rare or non-existent
   743   // updates is via interrupts. Even then this should be rare or non-existent
   744   // and we don't care that much anyway.
   744   // and we don't care that much anyway.
   745 
   745 
   746   int index = _jmp_ring_index;
   746   int index = _jmp_ring_index;
   747   _jmp_ring_index = (index + 1 ) & (jump_ring_buffer_size - 1);
   747   _jmp_ring_index = (index + 1) & (jump_ring_buffer_size - 1);
   748   _jmp_ring[index]._target = (intptr_t) target;
   748   _jmp_ring[index]._target = (intptr_t) target;
   749   _jmp_ring[index]._instruction = (intptr_t) instr;
   749   _jmp_ring[index]._instruction = (intptr_t) instr;
   750   _jmp_ring[index]._file = file;
   750   _jmp_ring[index]._file = file;
   751   _jmp_ring[index]._line = line;
   751   _jmp_ring[index]._line = line;
   752 }
   752 }
   753 #endif /* PRODUCT */
   753 #endif // PRODUCT
   754 
   754 
   755 // Called by flat profiler
   755 // Called by flat profiler
   756 // Callers have already called wait_for_ext_suspend_completion
   756 // Callers have already called wait_for_ext_suspend_completion
   757 // The assertion for that is currently too complex to put here:
   757 // The assertion for that is currently too complex to put here:
   758 bool JavaThread::profile_last_Java_frame(frame* _fr) {
   758 bool JavaThread::profile_last_Java_frame(frame* _fr) {
   832 }
   832 }
   833 
   833 
   834 // Thread::print_on_error() is called by fatal error handler. Don't use
   834 // Thread::print_on_error() is called by fatal error handler. Don't use
   835 // any lock or allocate memory.
   835 // any lock or allocate memory.
   836 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
   836 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
   837   if (is_VM_thread())                  st->print("VMThread");
   837   if (is_VM_thread())                 st->print("VMThread");
   838   else if (is_Compiler_thread())            st->print("CompilerThread");
   838   else if (is_Compiler_thread())      st->print("CompilerThread");
   839   else if (is_Java_thread())                st->print("JavaThread");
   839   else if (is_Java_thread())          st->print("JavaThread");
   840   else if (is_GC_task_thread())             st->print("GCTaskThread");
   840   else if (is_GC_task_thread())       st->print("GCTaskThread");
   841   else if (is_Watcher_thread())             st->print("WatcherThread");
   841   else if (is_Watcher_thread())       st->print("WatcherThread");
   842   else if (is_ConcurrentGC_thread())        st->print("ConcurrentGCThread");
   842   else if (is_ConcurrentGC_thread())  st->print("ConcurrentGCThread");
   843   else st->print("Thread");
   843   else                                st->print("Thread");
   844 
   844 
   845   st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
   845   st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
   846             _stack_base - _stack_size, _stack_base);
   846             _stack_base - _stack_size, _stack_base);
   847 
   847 
   848   if (osthread()) {
   848   if (osthread()) {
   881 // The flag: potential_vm_operation notifies if this particular safepoint state could potential
   881 // The flag: potential_vm_operation notifies if this particular safepoint state could potential
   882 // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that
   882 // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that
   883 // no threads which allow_vm_block's are held
   883 // no threads which allow_vm_block's are held
   884 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
   884 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
   885   // Check if current thread is allowed to block at a safepoint
   885   // Check if current thread is allowed to block at a safepoint
   886   if (!(_allow_safepoint_count == 0))
   886   if (!(_allow_safepoint_count == 0)) {
   887     fatal("Possible safepoint reached by thread that does not allow it");
   887     fatal("Possible safepoint reached by thread that does not allow it");
       
   888   }
   888   if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
   889   if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
   889     fatal("LEAF method calling lock?");
   890     fatal("LEAF method calling lock?");
   890   }
   891   }
   891 
   892 
   892 #ifdef ASSERT
   893 #ifdef ASSERT
   989   }
   990   }
   990   return main_instance;
   991   return main_instance;
   991 }
   992 }
   992 
   993 
   993 // Creates the initial Thread
   994 // Creates the initial Thread
   994 static oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) {
   995 static oop create_initial_thread(Handle thread_group, JavaThread* thread,
       
   996                                  TRAPS) {
   995   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_NULL);
   997   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_NULL);
   996   instanceKlassHandle klass (THREAD, k);
   998   instanceKlassHandle klass (THREAD, k);
   997   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL);
   999   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL);
   998 
  1000 
   999   java_lang_Thread::set_thread(thread_oop(), thread);
  1001   java_lang_Thread::set_thread(thread_oop(), thread);
  1033   bool found = k != NULL &&
  1035   bool found = k != NULL &&
  1034                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(),
  1036                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(),
  1035                                                         vmSymbols::string_signature(), &fd);
  1037                                                         vmSymbols::string_signature(), &fd);
  1036   if (found) {
  1038   if (found) {
  1037     oop name_oop = k->java_mirror()->obj_field(fd.offset());
  1039     oop name_oop = k->java_mirror()->obj_field(fd.offset());
  1038     if (name_oop == NULL)
  1040     if (name_oop == NULL) {
  1039       return NULL;
  1041       return NULL;
       
  1042     }
  1040     const char* name = java_lang_String::as_utf8_string(name_oop,
  1043     const char* name = java_lang_String::as_utf8_string(name_oop,
  1041                                                         java_runtime_name,
  1044                                                         java_runtime_name,
  1042                                                         sizeof(java_runtime_name));
  1045                                                         sizeof(java_runtime_name));
  1043     return name;
  1046     return name;
  1044   } else {
  1047   } else {
  1054   bool found = k != NULL &&
  1057   bool found = k != NULL &&
  1055                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(),
  1058                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(),
  1056                                                         vmSymbols::string_signature(), &fd);
  1059                                                         vmSymbols::string_signature(), &fd);
  1057   if (found) {
  1060   if (found) {
  1058     oop name_oop = k->java_mirror()->obj_field(fd.offset());
  1061     oop name_oop = k->java_mirror()->obj_field(fd.offset());
  1059     if (name_oop == NULL)
  1062     if (name_oop == NULL) {
  1060       return NULL;
  1063       return NULL;
       
  1064     }
  1061     const char* name = java_lang_String::as_utf8_string(name_oop,
  1065     const char* name = java_lang_String::as_utf8_string(name_oop,
  1062                                                         java_runtime_version,
  1066                                                         java_runtime_version,
  1063                                                         sizeof(java_runtime_version));
  1067                                                         sizeof(java_runtime_version));
  1064     return name;
  1068     return name;
  1065   } else {
  1069   } else {
  1105                          value_str,
  1109                          value_str,
  1106                          CHECK);
  1110                          CHECK);
  1107 }
  1111 }
  1108 
  1112 
  1109 
  1113 
  1110 void JavaThread::allocate_threadObj(Handle thread_group, char* thread_name, bool daemon, TRAPS) {
  1114 void JavaThread::allocate_threadObj(Handle thread_group, char* thread_name,
       
  1115                                     bool daemon, TRAPS) {
  1111   assert(thread_group.not_null(), "thread group should be specified");
  1116   assert(thread_group.not_null(), "thread group should be specified");
  1112   assert(threadObj() == NULL, "should only create Java thread object once");
  1117   assert(threadObj() == NULL, "should only create Java thread object once");
  1113 
  1118 
  1114   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
  1119   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
  1115   instanceKlassHandle klass (THREAD, k);
  1120   instanceKlassHandle klass (THREAD, k);
  1266       // another task gets enrolled
  1271       // another task gets enrolled
  1267       continue;
  1272       continue;
  1268     }
  1273     }
  1269 
  1274 
  1270     remaining -= time_slept;
  1275     remaining -= time_slept;
  1271     if (remaining <= 0)
  1276     if (remaining <= 0) {
  1272       break;
  1277       break;
       
  1278     }
  1273   }
  1279   }
  1274 
  1280 
  1275   return time_slept;
  1281   return time_slept;
  1276 }
  1282 }
  1277 
  1283 
  1385                           Mutex::_as_suspend_equivalent_flag);
  1391                           Mutex::_as_suspend_equivalent_flag);
  1386   }
  1392   }
  1387 }
  1393 }
  1388 
  1394 
  1389 void WatcherThread::unpark() {
  1395 void WatcherThread::unpark() {
  1390   MutexLockerEx ml(PeriodicTask_lock->owned_by_self() ? NULL : PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
  1396   MutexLockerEx ml(PeriodicTask_lock->owned_by_self()
       
  1397                    ? NULL
       
  1398                    : PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
  1391   PeriodicTask_lock->notify();
  1399   PeriodicTask_lock->notify();
  1392 }
  1400 }
  1393 
  1401 
  1394 void WatcherThread::print_on(outputStream* st) const {
  1402 void WatcherThread::print_on(outputStream* st) const {
  1395   st->print("\"%s\" ", name());
  1403   st->print("\"%s\" ", name());
  1453 #ifndef PRODUCT
  1461 #ifndef PRODUCT
  1454   _jmp_ring_index = 0;
  1462   _jmp_ring_index = 0;
  1455   for (int ji = 0; ji < jump_ring_buffer_size; ji++) {
  1463   for (int ji = 0; ji < jump_ring_buffer_size; ji++) {
  1456     record_jump(NULL, NULL, NULL, 0);
  1464     record_jump(NULL, NULL, NULL, 0);
  1457   }
  1465   }
  1458 #endif /* PRODUCT */
  1466 #endif // PRODUCT
  1459 
  1467 
  1460   set_thread_profiler(NULL);
  1468   set_thread_profiler(NULL);
  1461   if (FlatProfiler::is_active()) {
  1469   if (FlatProfiler::is_active()) {
  1462     // This is where we would decide to either give each thread it's own profiler
  1470     // This is where we would decide to either give each thread it's own profiler
  1463     // or use one global one from FlatProfiler,
  1471     // or use one global one from FlatProfiler,
  2059 
  2067 
  2060   if (check_unsafe_error &&
  2068   if (check_unsafe_error &&
  2061       condition == _async_unsafe_access_error && !has_pending_exception()) {
  2069       condition == _async_unsafe_access_error && !has_pending_exception()) {
  2062     condition = _no_async_condition;  // done
  2070     condition = _no_async_condition;  // done
  2063     switch (thread_state()) {
  2071     switch (thread_state()) {
  2064     case _thread_in_vm:
  2072     case _thread_in_vm: {
  2065     {
       
  2066       JavaThread* THREAD = this;
  2073       JavaThread* THREAD = this;
  2067       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
  2074       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
  2068     }
  2075     }
  2069     case _thread_in_native:
  2076     case _thread_in_native: {
  2070     {
       
  2071       ThreadInVMfromNative tiv(this);
  2077       ThreadInVMfromNative tiv(this);
  2072       JavaThread* THREAD = this;
  2078       JavaThread* THREAD = this;
  2073       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
  2079       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
  2074     }
  2080     }
  2075     case _thread_in_Java:
  2081     case _thread_in_Java: {
  2076     {
       
  2077       ThreadInVMfromJava tiv(this);
  2082       ThreadInVMfromJava tiv(this);
  2078       JavaThread* THREAD = this;
  2083       JavaThread* THREAD = this;
  2079       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
  2084       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
  2080     }
  2085     }
  2081     default:
  2086     default:
  2212     uint32_t debug_bits = 0;
  2217     uint32_t debug_bits = 0;
  2213     // Warning: is_ext_suspend_completed() may temporarily drop the
  2218     // Warning: is_ext_suspend_completed() may temporarily drop the
  2214     // SR_lock to allow the thread to reach a stable thread state if
  2219     // SR_lock to allow the thread to reach a stable thread state if
  2215     // it is currently in a transient thread state.
  2220     // it is currently in a transient thread state.
  2216     if (is_ext_suspend_completed(false /* !called_by_wait */,
  2221     if (is_ext_suspend_completed(false /* !called_by_wait */,
  2217                                  SuspendRetryDelay, &debug_bits) ) {
  2222                                  SuspendRetryDelay, &debug_bits)) {
  2218       return;
  2223       return;
  2219     }
  2224     }
  2220   }
  2225   }
  2221 
  2226 
  2222   VM_ForceSafepoint vm_suspend;
  2227   VM_ForceSafepoint vm_suspend;
  2290 void JavaThread::verify_not_published() {
  2295 void JavaThread::verify_not_published() {
  2291   if (!Threads_lock->owned_by_self()) {
  2296   if (!Threads_lock->owned_by_self()) {
  2292     MutexLockerEx ml(Threads_lock,  Mutex::_no_safepoint_check_flag);
  2297     MutexLockerEx ml(Threads_lock,  Mutex::_no_safepoint_check_flag);
  2293     assert(!Threads::includes(this),
  2298     assert(!Threads::includes(this),
  2294            "java thread shouldn't have been published yet!");
  2299            "java thread shouldn't have been published yet!");
  2295   }
  2300   } else {
  2296   else {
       
  2297     assert(!Threads::includes(this),
  2301     assert(!Threads::includes(this),
  2298            "java thread shouldn't have been published yet!");
  2302            "java thread shouldn't have been published yet!");
  2299   }
  2303   }
  2300 }
  2304 }
  2301 #endif
  2305 #endif
  2568         // Deoptimize only at particular bcis.  DeoptimizeOnlyAt
  2572         // Deoptimize only at particular bcis.  DeoptimizeOnlyAt
  2569         // consists of comma or carriage return separated numbers so
  2573         // consists of comma or carriage return separated numbers so
  2570         // search for the current bci in that string.
  2574         // search for the current bci in that string.
  2571         address pc = fst.current()->pc();
  2575         address pc = fst.current()->pc();
  2572         nmethod* nm =  (nmethod*) fst.current()->cb();
  2576         nmethod* nm =  (nmethod*) fst.current()->cb();
  2573         ScopeDesc* sd = nm->scope_desc_at( pc);
  2577         ScopeDesc* sd = nm->scope_desc_at(pc);
  2574         char buffer[8];
  2578         char buffer[8];
  2575         jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
  2579         jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
  2576         size_t len = strlen(buffer);
  2580         size_t len = strlen(buffer);
  2577         const char * found = strstr(DeoptimizeOnlyAt, buffer);
  2581         const char * found = strstr(DeoptimizeOnlyAt, buffer);
  2578         while (found != NULL) {
  2582         while (found != NULL) {
  2777 void JavaThread::print_thread_state_on(outputStream *st) const {
  2781 void JavaThread::print_thread_state_on(outputStream *st) const {
  2778   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
  2782   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
  2779 };
  2783 };
  2780 void JavaThread::print_thread_state() const {
  2784 void JavaThread::print_thread_state() const {
  2781   print_thread_state_on(tty);
  2785   print_thread_state_on(tty);
  2782 };
  2786 }
  2783 #endif // PRODUCT
  2787 #endif // PRODUCT
  2784 
  2788 
  2785 // Called by Threads::print() for VM_PrintThreads operation
  2789 // Called by Threads::print() for VM_PrintThreads operation
  2786 void JavaThread::print_on(outputStream *st) const {
  2790 void JavaThread::print_on(outputStream *st) const {
  2787   st->print("\"%s\" ", get_thread_name());
  2791   st->print("\"%s\" ", get_thread_name());
  2863   oop thread_obj = threadObj();
  2867   oop thread_obj = threadObj();
  2864   if (thread_obj != NULL) {
  2868   if (thread_obj != NULL) {
  2865     typeArrayOop name = java_lang_Thread::name(thread_obj);
  2869     typeArrayOop name = java_lang_Thread::name(thread_obj);
  2866     if (name != NULL) {
  2870     if (name != NULL) {
  2867       if (buf == NULL) {
  2871       if (buf == NULL) {
  2868         name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
  2872         name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR),
       
  2873                                     name->length());
       
  2874       } else {
       
  2875         name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR),
       
  2876                                     name->length(), buf, buflen);
  2869       }
  2877       }
  2870       else {
  2878     } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
  2871         name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length(), buf, buflen);
       
  2872       }
       
  2873     }
       
  2874     else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
       
  2875       name_str = "<no-name - thread is attaching>";
  2879       name_str = "<no-name - thread is attaching>";
  2876     }
  2880     } else {
  2877     else {
       
  2878       name_str = Thread::name();
  2881       name_str = Thread::name();
  2879     }
  2882     }
  2880   }
  2883   } else {
  2881   else {
       
  2882     name_str = Thread::name();
  2884     name_str = Thread::name();
  2883   }
  2885   }
  2884   assert(name_str != NULL, "unexpected NULL thread name");
  2886   assert(name_str != NULL, "unexpected NULL thread name");
  2885   return name_str;
  2887   return name_str;
  2886 }
  2888 }
  3163   assert(thread->is_Compiler_thread(), "must be compiler thread");
  3165   assert(thread->is_Compiler_thread(), "must be compiler thread");
  3164   CompileBroker::compiler_thread_loop();
  3166   CompileBroker::compiler_thread_loop();
  3165 }
  3167 }
  3166 
  3168 
  3167 // Create a CompilerThread
  3169 // Create a CompilerThread
  3168 CompilerThread::CompilerThread(CompileQueue* queue, CompilerCounters* counters)
  3170 CompilerThread::CompilerThread(CompileQueue* queue,
  3169 : JavaThread(&compiler_thread_entry) {
  3171                                CompilerCounters* counters)
       
  3172                                : JavaThread(&compiler_thread_entry) {
  3170   _env   = NULL;
  3173   _env   = NULL;
  3171   _log   = NULL;
  3174   _log   = NULL;
  3172   _task  = NULL;
  3175   _task  = NULL;
  3173   _queue = queue;
  3176   _queue = queue;
  3174   _counters = counters;
  3177   _counters = counters;
  3229   // considering that WatchThread terminates when the VM is on the way to
  3232   // considering that WatchThread terminates when the VM is on the way to
  3230   // exit at safepoint, the chance of the above is extremely small. The right
  3233   // exit at safepoint, the chance of the above is extremely small. The right
  3231   // way to prevent termination of WatcherThread would be to acquire
  3234   // way to prevent termination of WatcherThread would be to acquire
  3232   // Terminator_lock, but we can't do that without violating the lock rank
  3235   // Terminator_lock, but we can't do that without violating the lock rank
  3233   // checking in some cases.
  3236   // checking in some cases.
  3234   if (wt != NULL)
  3237   if (wt != NULL) {
  3235     tc->do_thread(wt);
  3238     tc->do_thread(wt);
       
  3239   }
  3236 
  3240 
  3237   // If CompilerThreads ever become non-JavaThreads, add them here
  3241   // If CompilerThreads ever become non-JavaThreads, add them here
  3238 }
  3242 }
  3239 
  3243 
  3240 
  3244 
  3288   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
  3292   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
  3289   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
  3293   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
  3290 }
  3294 }
  3291 
  3295 
  3292 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
  3296 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
  3293 
       
  3294   extern void JDK_Version_init();
  3297   extern void JDK_Version_init();
  3295 
  3298 
  3296   // Check version
  3299   // Check version
  3297   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
  3300   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
  3298 
  3301 
  3420   // Create the VMThread
  3423   // Create the VMThread
  3421   { TraceTime timer("Start VMThread", TraceStartupTime);
  3424   { TraceTime timer("Start VMThread", TraceStartupTime);
  3422     VMThread::create();
  3425     VMThread::create();
  3423     Thread* vmthread = VMThread::vm_thread();
  3426     Thread* vmthread = VMThread::vm_thread();
  3424 
  3427 
  3425     if (!os::create_thread(vmthread, os::vm_thread))
  3428     if (!os::create_thread(vmthread, os::vm_thread)) {
  3426       vm_exit_during_initialization("Cannot create VM thread. Out of system resources.");
  3429       vm_exit_during_initialization("Cannot create VM thread. "
       
  3430                                     "Out of system resources.");
       
  3431     }
  3427 
  3432 
  3428     // Wait for the VM thread to become ready, and VMThread::run to initialize
  3433     // Wait for the VM thread to become ready, and VMThread::run to initialize
  3429     // Monitors can have spurious returns, must always check another state flag
  3434     // Monitors can have spurious returns, must always check another state flag
  3430     {
  3435     {
  3431       MutexLocker ml(Notify_lock);
  3436       MutexLocker ml(Notify_lock);
  3611   typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
  3616   typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
  3612 }
  3617 }
  3613 // Find a command line agent library and return its entry point for
  3618 // Find a command line agent library and return its entry point for
  3614 //         -agentlib:  -agentpath:   -Xrun
  3619 //         -agentlib:  -agentpath:   -Xrun
  3615 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
  3620 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
  3616 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, const char *on_load_symbols[], size_t num_symbol_entries) {
  3621 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent,
       
  3622                                     const char *on_load_symbols[],
       
  3623                                     size_t num_symbol_entries) {
  3617   OnLoadEntry_t on_load_entry = NULL;
  3624   OnLoadEntry_t on_load_entry = NULL;
  3618   void *library = NULL;
  3625   void *library = NULL;
  3619 
  3626 
  3620   if (!agent->valid()) {
  3627   if (!agent->valid()) {
  3621     char buffer[JVM_MAXPATHLEN];
  3628     char buffer[JVM_MAXPATHLEN];
  4004       _number_of_non_daemon_threads--;
  4011       _number_of_non_daemon_threads--;
  4005       daemon = false;
  4012       daemon = false;
  4006 
  4013 
  4007       // Only one thread left, do a notify on the Threads_lock so a thread waiting
  4014       // Only one thread left, do a notify on the Threads_lock so a thread waiting
  4008       // on destroy_vm will wake up.
  4015       // on destroy_vm will wake up.
  4009       if (number_of_non_daemon_threads() == 1)
  4016       if (number_of_non_daemon_threads() == 1) {
  4010         Threads_lock->notify_all();
  4017         Threads_lock->notify_all();
       
  4018       }
  4011     }
  4019     }
  4012     ThreadService::remove_thread(p, daemon);
  4020     ThreadService::remove_thread(p, daemon);
  4013 
  4021 
  4014     // Make sure that safepoint code disregard this thread. This is needed since
  4022     // Make sure that safepoint code disregard this thread. This is needed since
  4015     // the thread might mess around with locks after this point. This can cause it
  4023     // the thread might mess around with locks after this point. This can cause it
  4111 }
  4119 }
  4112 
  4120 
  4113 
  4121 
  4114 // Get count Java threads that are waiting to enter the specified monitor.
  4122 // Get count Java threads that are waiting to enter the specified monitor.
  4115 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
  4123 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
  4116                                                          address monitor, bool doLock) {
  4124                                                          address monitor,
       
  4125                                                          bool doLock) {
  4117   assert(doLock || SafepointSynchronize::is_at_safepoint(),
  4126   assert(doLock || SafepointSynchronize::is_at_safepoint(),
  4118          "must grab Threads_lock or be at safepoint");
  4127          "must grab Threads_lock or be at safepoint");
  4119   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
  4128   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
  4120 
  4129 
  4121   int i = 0;
  4130   int i = 0;
  4133   }
  4142   }
  4134   return result;
  4143   return result;
  4135 }
  4144 }
  4136 
  4145 
  4137 
  4146 
  4138 JavaThread *Threads::owning_thread_from_monitor_owner(address owner, bool doLock) {
  4147 JavaThread *Threads::owning_thread_from_monitor_owner(address owner,
       
  4148                                                       bool doLock) {
  4139   assert(doLock ||
  4149   assert(doLock ||
  4140          Threads_lock->owned_by_self() ||
  4150          Threads_lock->owned_by_self() ||
  4141          SafepointSynchronize::is_at_safepoint(),
  4151          SafepointSynchronize::is_at_safepoint(),
  4142          "must grab Threads_lock or be at safepoint");
  4152          "must grab Threads_lock or be at safepoint");
  4143 
  4153 
  4154   // Cannot assert on lack of success here since this function may be
  4164   // Cannot assert on lack of success here since this function may be
  4155   // used by code that is trying to report useful problem information
  4165   // used by code that is trying to report useful problem information
  4156   // like deadlock detection.
  4166   // like deadlock detection.
  4157   if (UseHeavyMonitors) return NULL;
  4167   if (UseHeavyMonitors) return NULL;
  4158 
  4168 
  4159   //
       
  4160   // If we didn't find a matching Java thread and we didn't force use of
  4169   // If we didn't find a matching Java thread and we didn't force use of
  4161   // heavyweight monitors, then the owner is the stack address of the
  4170   // heavyweight monitors, then the owner is the stack address of the
  4162   // Lock Word in the owning Java thread's stack.
  4171   // Lock Word in the owning Java thread's stack.
  4163   //
  4172   //
  4164   JavaThread* the_owner = NULL;
  4173   JavaThread* the_owner = NULL;
  4174   // cannot assert on lack of success here; see above comment
  4183   // cannot assert on lack of success here; see above comment
  4175   return the_owner;
  4184   return the_owner;
  4176 }
  4185 }
  4177 
  4186 
  4178 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
  4187 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
  4179 void Threads::print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks) {
  4188 void Threads::print_on(outputStream* st, bool print_stacks,
       
  4189                        bool internal_format, bool print_concurrent_locks) {
  4180   char buf[32];
  4190   char buf[32];
  4181   st->print_cr("%s", os::local_time_string(buf, sizeof(buf)));
  4191   st->print_cr("%s", os::local_time_string(buf, sizeof(buf)));
  4182 
  4192 
  4183   st->print_cr("Full thread dump %s (%s %s):",
  4193   st->print_cr("Full thread dump %s (%s %s):",
  4184                Abstract_VM_Version::vm_name(),
  4194                Abstract_VM_Version::vm_name(),
  4185                Abstract_VM_Version::vm_release(),
  4195                Abstract_VM_Version::vm_release(),
  4186                Abstract_VM_Version::vm_info_string()
  4196                Abstract_VM_Version::vm_info_string());
  4187               );
       
  4188   st->cr();
  4197   st->cr();
  4189 
  4198 
  4190 #if INCLUDE_ALL_GCS
  4199 #if INCLUDE_ALL_GCS
  4191   // Dump concurrent locks
  4200   // Dump concurrent locks
  4192   ConcurrentLocksDump concurrent_locks;
  4201   ConcurrentLocksDump concurrent_locks;
  4227 
  4236 
  4228 // Threads::print_on_error() is called by fatal error handler. It's possible
  4237 // Threads::print_on_error() is called by fatal error handler. It's possible
  4229 // that VM is not at safepoint and/or current thread is inside signal handler.
  4238 // that VM is not at safepoint and/or current thread is inside signal handler.
  4230 // Don't print stack trace, as the stack may not be walkable. Don't allocate
  4239 // Don't print stack trace, as the stack may not be walkable. Don't allocate
  4231 // memory (even in resource area), it might deadlock the error handler.
  4240 // memory (even in resource area), it might deadlock the error handler.
  4232 void Threads::print_on_error(outputStream* st, Thread* current, char* buf, int buflen) {
  4241 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
       
  4242                              int buflen) {
  4233   bool found_current = false;
  4243   bool found_current = false;
  4234   st->print_cr("Java Threads: ( => current thread )");
  4244   st->print_cr("Java Threads: ( => current thread )");
  4235   ALL_JAVA_THREADS(thread) {
  4245   ALL_JAVA_THREADS(thread) {
  4236     bool is_current = (current == thread);
  4246     bool is_current = (current == thread);
  4237     found_current = found_current || is_current;
  4247     found_current = found_current || is_current;
  4299 // cache-coherency traffic.
  4309 // cache-coherency traffic.
  4300 
  4310 
  4301 
  4311 
  4302 typedef volatile int SpinLockT;
  4312 typedef volatile int SpinLockT;
  4303 
  4313 
  4304 void Thread::SpinAcquire (volatile int * adr, const char * LockName) {
  4314 void Thread::SpinAcquire(volatile int * adr, const char * LockName) {
  4305   if (Atomic::cmpxchg (1, adr, 0) == 0) {
  4315   if (Atomic::cmpxchg (1, adr, 0) == 0) {
  4306     return;   // normal fast-path return
  4316     return;   // normal fast-path return
  4307   }
  4317   }
  4308 
  4318 
  4309   // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
  4319   // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
  4326     }
  4336     }
  4327     if (Atomic::cmpxchg(1, adr, 0) == 0) return;
  4337     if (Atomic::cmpxchg(1, adr, 0) == 0) return;
  4328   }
  4338   }
  4329 }
  4339 }
  4330 
  4340 
  4331 void Thread::SpinRelease (volatile int * adr) {
  4341 void Thread::SpinRelease(volatile int * adr) {
  4332   assert(*adr != 0, "invariant");
  4342   assert(*adr != 0, "invariant");
  4333   OrderAccess::fence();      // guarantee at least release consistency.
  4343   OrderAccess::fence();      // guarantee at least release consistency.
  4334   // Roach-motel semantics.
  4344   // Roach-motel semantics.
  4335   // It's safe if subsequent LDs and STs float "up" into the critical section,
  4345   // It's safe if subsequent LDs and STs float "up" into the critical section,
  4336   // but prior LDs and STs within the critical section can't be allowed
  4346   // but prior LDs and STs within the critical section can't be allowed
  4395 
  4405 
  4396 
  4406 
  4397 typedef volatile intptr_t MutexT;      // Mux Lock-word
  4407 typedef volatile intptr_t MutexT;      // Mux Lock-word
  4398 enum MuxBits { LOCKBIT = 1 };
  4408 enum MuxBits { LOCKBIT = 1 };
  4399 
  4409 
  4400 void Thread::muxAcquire (volatile intptr_t * Lock, const char * LockName) {
  4410 void Thread::muxAcquire(volatile intptr_t * Lock, const char * LockName) {
  4401   intptr_t w = Atomic::cmpxchg_ptr(LOCKBIT, Lock, 0);
  4411   intptr_t w = Atomic::cmpxchg_ptr(LOCKBIT, Lock, 0);
  4402   if (w == 0) return;
  4412   if (w == 0) return;
  4403   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4413   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4404     return;
  4414     return;
  4405   }
  4415   }
  4441       Self->park();
  4451       Self->park();
  4442     }
  4452     }
  4443   }
  4453   }
  4444 }
  4454 }
  4445 
  4455 
  4446 void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) {
  4456 void Thread::muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev) {
  4447   intptr_t w = Atomic::cmpxchg_ptr(LOCKBIT, Lock, 0);
  4457   intptr_t w = Atomic::cmpxchg_ptr(LOCKBIT, Lock, 0);
  4448   if (w == 0) return;
  4458   if (w == 0) return;
  4449   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4459   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4450     return;
  4460     return;
  4451   }
  4461   }
  4526 // All paths through muxRelease() will execute a CAS.
  4536 // All paths through muxRelease() will execute a CAS.
  4527 // Release consistency -- We depend on the CAS in muxRelease() to provide full
  4537 // Release consistency -- We depend on the CAS in muxRelease() to provide full
  4528 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations
  4538 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations
  4529 // executed within the critical section are complete and globally visible before the
  4539 // executed within the critical section are complete and globally visible before the
  4530 // store (CAS) to the lock-word that releases the lock becomes globally visible.
  4540 // store (CAS) to the lock-word that releases the lock becomes globally visible.
  4531 void Thread::muxRelease (volatile intptr_t * Lock)  {
  4541 void Thread::muxRelease(volatile intptr_t * Lock)  {
  4532   for (;;) {
  4542   for (;;) {
  4533     const intptr_t w = Atomic::cmpxchg_ptr(0, Lock, LOCKBIT);
  4543     const intptr_t w = Atomic::cmpxchg_ptr(0, Lock, LOCKBIT);
  4534     assert(w & LOCKBIT, "invariant");
  4544     assert(w & LOCKBIT, "invariant");
  4535     if (w == LOCKBIT) return;
  4545     if (w == LOCKBIT) return;
  4536     ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT);
  4546     ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT);