1 /* 2 * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "jvm.h" 27 #include "classfile/classLoader.hpp" 28 #include "classfile/javaClasses.hpp" 29 #include "classfile/moduleEntry.hpp" 30 #include "classfile/systemDictionary.hpp" 31 #include "classfile/vmSymbols.hpp" 32 #include "code/codeCache.hpp" 33 #include "code/scopeDesc.hpp" 34 #include "compiler/compileBroker.hpp" 35 #include "compiler/compileTask.hpp" 36 #include "gc/shared/barrierSet.hpp" 37 #include "gc/shared/gcId.hpp" 38 #include "gc/shared/gcLocker.inline.hpp" 39 #include "gc/shared/workgroup.hpp" 40 #include "interpreter/interpreter.hpp" 41 #include "interpreter/linkResolver.hpp" 42 #include "interpreter/oopMapCache.hpp" 43 #include "jfr/jfrEvents.hpp" 44 #include "jfr/support/jfrThreadId.hpp" 45 #include "jvmtifiles/jvmtiEnv.hpp" 46 #include "logging/log.hpp" 47 #include "logging/logConfiguration.hpp" 48 #include "logging/logStream.hpp" 49 #include "memory/allocation.inline.hpp" 50 #include "memory/metaspaceShared.hpp" 51 #include "memory/oopFactory.hpp" 52 #include "memory/resourceArea.hpp" 53 #include "memory/universe.hpp" 54 #include "oops/access.inline.hpp" 55 #include "oops/instanceKlass.hpp" 56 #include "oops/objArrayOop.hpp" 57 #include "oops/oop.inline.hpp" 58 #include "oops/symbol.hpp" 59 #include "oops/typeArrayOop.inline.hpp" 60 #include "oops/verifyOopClosure.hpp" 61 #include "prims/jvm_misc.hpp" 62 #include "prims/jvmtiExport.hpp" 63 #include "prims/jvmtiThreadState.hpp" 64 #include "prims/privilegedStack.hpp" 65 #include "runtime/arguments.hpp" 66 #include "runtime/atomic.hpp" 67 #include "runtime/biasedLocking.hpp" 68 #include "runtime/flags/jvmFlagConstraintList.hpp" 69 #include "runtime/flags/jvmFlagRangeList.hpp" 70 #include "runtime/flags/jvmFlagWriteableList.hpp" 71 #include "runtime/deoptimization.hpp" 72 #include "runtime/frame.inline.hpp" 73 #include "runtime/handshake.hpp" 74 #include "runtime/init.hpp" 75 #include "runtime/interfaceSupport.inline.hpp" 76 #include "runtime/java.hpp" 77 #include "runtime/javaCalls.hpp" 78 #include "runtime/jniHandles.inline.hpp" 79 #include "runtime/jniPeriodicChecker.hpp" 80 #include "runtime/memprofiler.hpp" 81 #include "runtime/mutexLocker.hpp" 82 #include "runtime/objectMonitor.hpp" 83 #include "runtime/orderAccess.hpp" 84 #include "runtime/osThread.hpp" 85 #include "runtime/prefetch.inline.hpp" 86 #include "runtime/safepoint.hpp" 87 #include "runtime/safepointMechanism.inline.hpp" 88 #include "runtime/sharedRuntime.hpp" 89 #include "runtime/statSampler.hpp" 90 #include "runtime/stubRoutines.hpp" 91 #include "runtime/sweeper.hpp" 92 #include "runtime/task.hpp" 93 #include "runtime/thread.inline.hpp" 94 #include "runtime/threadCritical.hpp" 95 #include "runtime/threadSMR.inline.hpp" 96 #include "runtime/threadStatisticalInfo.hpp" 97 #include "runtime/timer.hpp" 98 #include "runtime/timerTrace.hpp" 99 #include "runtime/vframe.inline.hpp" 100 #include "runtime/vframeArray.hpp" 101 #include "runtime/vframe_hp.hpp" 102 #include "runtime/vmThread.hpp" 103 #include "runtime/vm_operations.hpp" 104 #include "runtime/vm_version.hpp" 105 #include "services/attachListener.hpp" 106 #include "services/management.hpp" 107 #include "services/memTracker.hpp" 108 #include "services/threadService.hpp" 109 #include "utilities/align.hpp" 110 #include "utilities/copy.hpp" 111 #include "utilities/defaultStream.hpp" 112 #include "utilities/dtrace.hpp" 113 #include "utilities/events.hpp" 114 #include "utilities/macros.hpp" 115 #include "utilities/preserveException.hpp" 116 #include "utilities/vmError.hpp" 117 #if INCLUDE_JVMCI 118 #include "jvmci/jvmciCompiler.hpp" 119 #include "jvmci/jvmciRuntime.hpp" 120 #include "logging/logHandle.hpp" 121 #endif 122 #ifdef COMPILER1 123 #include "c1/c1_Compiler.hpp" 124 #endif 125 #ifdef COMPILER2 126 #include "opto/c2compiler.hpp" 127 #include "opto/idealGraphPrinter.hpp" 128 #endif 129 #if INCLUDE_RTM_OPT 130 #include "runtime/rtmLocking.hpp" 131 #endif 132 #if INCLUDE_JFR 133 #include "jfr/jfr.hpp" 134 #endif 135 136 // Initialization after module runtime initialization 137 void universe_post_module_init(); // must happen after call_initPhase2 138 139 #ifdef DTRACE_ENABLED 140 141 // Only bother with this argument setup if dtrace is available 142 143 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START 144 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP 145 146 #define DTRACE_THREAD_PROBE(probe, javathread) \ 147 { \ 148 ResourceMark rm(this); \ 149 int len = 0; \ 150 const char* name = (javathread)->get_thread_name(); \ 151 len = strlen(name); \ 152 HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */ \ 153 (char *) name, len, \ 154 java_lang_Thread::thread_id((javathread)->threadObj()), \ 155 (uintptr_t) (javathread)->osthread()->thread_id(), \ 156 java_lang_Thread::is_daemon((javathread)->threadObj())); \ 157 } 158 159 #else // ndef DTRACE_ENABLED 160 161 #define DTRACE_THREAD_PROBE(probe, javathread) 162 163 #endif // ndef DTRACE_ENABLED 164 165 #ifndef USE_LIBRARY_BASED_TLS_ONLY 166 // Current thread is maintained as a thread-local variable 167 THREAD_LOCAL_DECL Thread* Thread::_thr_current = NULL; 168 #endif 169 // Class hierarchy 170 // - Thread 171 // - VMThread 172 // - WatcherThread 173 // - ConcurrentMarkSweepThread 174 // - JavaThread 175 // - CompilerThread 176 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 = align_up(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 (aligned_addr != real_malloc_addr) { 191 log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT, 192 p2i(real_malloc_addr), 193 p2i(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 } 202 203 void Thread::operator delete(void* p) { 204 if (UseBiasedLocking) { 205 FreeHeap(((Thread*) p)->_real_malloc_address); 206 } else { 207 FreeHeap(p); 208 } 209 } 210 211 void JavaThread::smr_delete() { 212 if (_on_thread_list) { 213 ThreadsSMRSupport::smr_delete(this); 214 } else { 215 delete this; 216 } 217 } 218 219 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread, 220 // JavaThread 221 222 223 Thread::Thread() { 224 // stack and get_thread 225 set_stack_base(NULL); 226 set_stack_size(0); 227 set_self_raw_id(0); 228 set_lgrp_id(-1); 229 DEBUG_ONLY(clear_suspendible_thread();) 230 231 // allocated data structures 232 set_osthread(NULL); 233 set_resource_area(new (mtThread)ResourceArea()); 234 DEBUG_ONLY(_current_resource_mark = NULL;) 235 set_handle_area(new (mtThread) HandleArea(NULL)); 236 set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true)); 237 set_active_handles(NULL); 238 set_free_handle_block(NULL); 239 set_last_handle_mark(NULL); 240 241 // This initial value ==> never claimed. 242 _oops_do_parity = 0; 243 _threads_hazard_ptr = NULL; 244 _threads_list_ptr = NULL; 245 _nested_threads_hazard_ptr_cnt = 0; 246 _rcu_counter = 0; 247 248 // the handle mark links itself to last_handle_mark 249 new HandleMark(this); 250 251 // plain initialization 252 debug_only(_owned_locks = NULL;) 253 debug_only(_allow_allocation_count = 0;) 254 NOT_PRODUCT(_allow_safepoint_count = 0;) 255 NOT_PRODUCT(_skip_gcalot = false;) 256 _jvmti_env_iteration_count = 0; 257 set_allocated_bytes(0); 258 _vm_operation_started_count = 0; 259 _vm_operation_completed_count = 0; 260 _current_pending_monitor = NULL; 261 _current_pending_monitor_is_from_java = true; 262 _current_waiting_monitor = NULL; 263 _num_nested_signal = 0; 264 omFreeList = NULL; 265 omFreeCount = 0; 266 omFreeProvision = 32; 267 omInUseList = NULL; 268 omInUseCount = 0; 269 270 #ifdef ASSERT 271 _visited_for_critical_count = false; 272 #endif 273 274 _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true, 275 Monitor::_safepoint_check_sometimes); 276 _suspend_flags = 0; 277 278 _behaviour_provider = NULL; 279 280 // thread-specific hashCode stream generator state - Marsaglia shift-xor form 281 _hashStateX = os::random(); 282 _hashStateY = 842502087; 283 _hashStateZ = 0x8767; // (int)(3579807591LL & 0xffff) ; 284 _hashStateW = 273326509; 285 286 _OnTrap = 0; 287 _schedctl = NULL; 288 _Stalled = 0; 289 _TypeTag = 0x2BAD; 290 291 // Many of the following fields are effectively final - immutable 292 // Note that nascent threads can't use the Native Monitor-Mutex 293 // construct until the _MutexEvent is initialized ... 294 // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents 295 // we might instead use a stack of ParkEvents that we could provision on-demand. 296 // The stack would act as a cache to avoid calls to ParkEvent::Allocate() 297 // and ::Release() 298 _ParkEvent = ParkEvent::Allocate(this); 299 _SleepEvent = ParkEvent::Allocate(this); 300 _MutexEvent = ParkEvent::Allocate(this); 301 _MuxEvent = ParkEvent::Allocate(this); 302 303 #ifdef CHECK_UNHANDLED_OOPS 304 if (CheckUnhandledOops) { 305 _unhandled_oops = new UnhandledOops(this); 306 } 307 #endif // CHECK_UNHANDLED_OOPS 308 #ifdef ASSERT 309 if (UseBiasedLocking) { 310 assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed"); 311 assert(this == _real_malloc_address || 312 this == align_up(_real_malloc_address, (int)markOopDesc::biased_lock_alignment), 313 "bug in forced alignment of thread objects"); 314 } 315 #endif // ASSERT 316 317 // Notify the barrier set that a thread is being created. Note that the 318 // main thread is created before a barrier set is available. The call to 319 // BarrierSet::on_thread_create() for the main thread is therefore deferred 320 // until it calls BarrierSet::set_barrier_set(). 321 BarrierSet* const barrier_set = BarrierSet::barrier_set(); 322 if (barrier_set != NULL) { 323 barrier_set->on_thread_create(this); 324 } 325 } 326 327 void Thread::initialize_thread_current() { 328 #ifndef USE_LIBRARY_BASED_TLS_ONLY 329 assert(_thr_current == NULL, "Thread::current already initialized"); 330 _thr_current = this; 331 #endif 332 assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized"); 333 ThreadLocalStorage::set_thread(this); 334 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!"); 335 } 336 337 void Thread::clear_thread_current() { 338 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!"); 339 #ifndef USE_LIBRARY_BASED_TLS_ONLY 340 _thr_current = NULL; 341 #endif 342 ThreadLocalStorage::set_thread(NULL); 343 } 344 345 void Thread::record_stack_base_and_size() { 346 set_stack_base(os::current_stack_base()); 347 set_stack_size(os::current_stack_size()); 348 // CR 7190089: on Solaris, primordial thread's stack is adjusted 349 // in initialize_thread(). Without the adjustment, stack size is 350 // incorrect if stack is set to unlimited (ulimit -s unlimited). 351 // So far, only Solaris has real implementation of initialize_thread(). 352 // 353 // set up any platform-specific state. 354 os::initialize_thread(this); 355 356 // Set stack limits after thread is initialized. 357 if (is_Java_thread()) { 358 ((JavaThread*) this)->set_stack_overflow_limit(); 359 ((JavaThread*) this)->set_reserved_stack_activation(stack_base()); 360 } 361 #if INCLUDE_NMT 362 // record thread's native stack, stack grows downward 363 MemTracker::record_thread_stack(stack_end(), stack_size()); 364 #endif // INCLUDE_NMT 365 log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: " 366 PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).", 367 os::current_thread_id(), p2i(stack_base() - stack_size()), 368 p2i(stack_base()), stack_size()/1024); 369 } 370 371 372 Thread::~Thread() { 373 JFR_ONLY(Jfr::on_thread_destruct(this);) 374 375 // Notify the barrier set that a thread is being destroyed. Note that a barrier 376 // set might not be available if we encountered errors during bootstrapping. 377 BarrierSet* const barrier_set = BarrierSet::barrier_set(); 378 if (barrier_set != NULL) { 379 barrier_set->on_thread_destroy(this); 380 } 381 382 383 // stack_base can be NULL if the thread is never started or exited before 384 // record_stack_base_and_size called. Although, we would like to ensure 385 // that all started threads do call record_stack_base_and_size(), there is 386 // not proper way to enforce that. 387 #if INCLUDE_NMT 388 if (_stack_base != NULL) { 389 MemTracker::release_thread_stack(stack_end(), stack_size()); 390 #ifdef ASSERT 391 set_stack_base(NULL); 392 #endif 393 } 394 #endif // INCLUDE_NMT 395 396 // deallocate data structures 397 delete resource_area(); 398 // since the handle marks are using the handle area, we have to deallocated the root 399 // handle mark before deallocating the thread's handle area, 400 assert(last_handle_mark() != NULL, "check we have an element"); 401 delete last_handle_mark(); 402 assert(last_handle_mark() == NULL, "check we have reached the end"); 403 404 // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads. 405 // We NULL out the fields for good hygiene. 406 ParkEvent::Release(_ParkEvent); _ParkEvent = NULL; 407 ParkEvent::Release(_SleepEvent); _SleepEvent = NULL; 408 ParkEvent::Release(_MutexEvent); _MutexEvent = NULL; 409 ParkEvent::Release(_MuxEvent); _MuxEvent = NULL; 410 411 delete handle_area(); 412 delete metadata_handles(); 413 414 // SR_handler uses this as a termination indicator - 415 // needs to happen before os::free_thread() 416 delete _SR_lock; 417 _SR_lock = NULL; 418 419 // osthread() can be NULL, if creation of thread failed. 420 if (osthread() != NULL) os::free_thread(osthread()); 421 422 // clear Thread::current if thread is deleting itself. 423 // Needed to ensure JNI correctly detects non-attached threads. 424 if (this == Thread::current()) { 425 clear_thread_current(); 426 } 427 428 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();) 429 } 430 431 // NOTE: dummy function for assertion purpose. 432 void Thread::run() { 433 ShouldNotReachHere(); 434 } 435 436 #ifdef ASSERT 437 // A JavaThread is considered "dangling" if it is not the current 438 // thread, has been added the Threads list, the system is not at a 439 // safepoint and the Thread is not "protected". 440 // 441 void Thread::check_for_dangling_thread_pointer(Thread *thread) { 442 assert(!thread->is_Java_thread() || Thread::current() == thread || 443 !((JavaThread *) thread)->on_thread_list() || 444 SafepointSynchronize::is_at_safepoint() || 445 ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread), 446 "possibility of dangling Thread pointer"); 447 } 448 #endif 449 450 ThreadPriority Thread::get_priority(const Thread* const thread) { 451 ThreadPriority priority; 452 // Can return an error! 453 (void)os::get_priority(thread, priority); 454 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found"); 455 return priority; 456 } 457 458 void Thread::set_priority(Thread* thread, ThreadPriority priority) { 459 debug_only(check_for_dangling_thread_pointer(thread);) 460 // Can return an error! 461 (void)os::set_priority(thread, priority); 462 } 463 464 465 void Thread::start(Thread* thread) { 466 // Start is different from resume in that its safety is guaranteed by context or 467 // being called from a Java method synchronized on the Thread object. 468 if (!DisableStartThread) { 469 if (thread->is_Java_thread()) { 470 // Initialize the thread state to RUNNABLE before starting this thread. 471 // Can not set it after the thread started because we do not know the 472 // exact thread state at that time. It could be in MONITOR_WAIT or 473 // in SLEEPING or some other state. 474 java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(), 475 java_lang_Thread::RUNNABLE); 476 } 477 os::start_thread(thread); 478 } 479 } 480 481 // Enqueue a VM_Operation to do the job for us - sometime later 482 void Thread::send_async_exception(oop java_thread, oop java_throwable) { 483 VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable); 484 VMThread::execute(vm_stop); 485 } 486 487 488 // Check if an external suspend request has completed (or has been 489 // cancelled). Returns true if the thread is externally suspended and 490 // false otherwise. 491 // 492 // The bits parameter returns information about the code path through 493 // the routine. Useful for debugging: 494 // 495 // set in is_ext_suspend_completed(): 496 // 0x00000001 - routine was entered 497 // 0x00000010 - routine return false at end 498 // 0x00000100 - thread exited (return false) 499 // 0x00000200 - suspend request cancelled (return false) 500 // 0x00000400 - thread suspended (return true) 501 // 0x00001000 - thread is in a suspend equivalent state (return true) 502 // 0x00002000 - thread is native and walkable (return true) 503 // 0x00004000 - thread is native_trans and walkable (needed retry) 504 // 505 // set in wait_for_ext_suspend_completion(): 506 // 0x00010000 - routine was entered 507 // 0x00020000 - suspend request cancelled before loop (return false) 508 // 0x00040000 - thread suspended before loop (return true) 509 // 0x00080000 - suspend request cancelled in loop (return false) 510 // 0x00100000 - thread suspended in loop (return true) 511 // 0x00200000 - suspend not completed during retry loop (return false) 512 513 // Helper class for tracing suspend wait debug bits. 514 // 515 // 0x00000100 indicates that the target thread exited before it could 516 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and 517 // 0x00080000 each indicate a cancelled suspend request so they don't 518 // count as wait failures either. 519 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000) 520 521 class TraceSuspendDebugBits : public StackObj { 522 private: 523 JavaThread * jt; 524 bool is_wait; 525 bool called_by_wait; // meaningful when !is_wait 526 uint32_t * bits; 527 528 public: 529 TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait, 530 uint32_t *_bits) { 531 jt = _jt; 532 is_wait = _is_wait; 533 called_by_wait = _called_by_wait; 534 bits = _bits; 535 } 536 537 ~TraceSuspendDebugBits() { 538 if (!is_wait) { 539 #if 1 540 // By default, don't trace bits for is_ext_suspend_completed() calls. 541 // That trace is very chatty. 542 return; 543 #else 544 if (!called_by_wait) { 545 // If tracing for is_ext_suspend_completed() is enabled, then only 546 // trace calls to it from wait_for_ext_suspend_completion() 547 return; 548 } 549 #endif 550 } 551 552 if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) { 553 if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) { 554 MutexLocker ml(Threads_lock); // needed for get_thread_name() 555 ResourceMark rm; 556 557 tty->print_cr( 558 "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)", 559 jt->get_thread_name(), *bits); 560 561 guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed"); 562 } 563 } 564 } 565 }; 566 #undef DEBUG_FALSE_BITS 567 568 569 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, 570 uint32_t *bits) { 571 TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits); 572 573 bool did_trans_retry = false; // only do thread_in_native_trans retry once 574 bool do_trans_retry; // flag to force the retry 575 576 *bits |= 0x00000001; 577 578 do { 579 do_trans_retry = false; 580 581 if (is_exiting()) { 582 // Thread is in the process of exiting. This is always checked 583 // first to reduce the risk of dereferencing a freed JavaThread. 584 *bits |= 0x00000100; 585 return false; 586 } 587 588 if (!is_external_suspend()) { 589 // Suspend request is cancelled. This is always checked before 590 // is_ext_suspended() to reduce the risk of a rogue resume 591 // confusing the thread that made the suspend request. 592 *bits |= 0x00000200; 593 return false; 594 } 595 596 if (is_ext_suspended()) { 597 // thread is suspended 598 *bits |= 0x00000400; 599 return true; 600 } 601 602 // Now that we no longer do hard suspends of threads running 603 // native code, the target thread can be changing thread state 604 // while we are in this routine: 605 // 606 // _thread_in_native -> _thread_in_native_trans -> _thread_blocked 607 // 608 // We save a copy of the thread state as observed at this moment 609 // and make our decision about suspend completeness based on the 610 // copy. This closes the race where the thread state is seen as 611 // _thread_in_native_trans in the if-thread_blocked check, but is 612 // seen as _thread_blocked in if-thread_in_native_trans check. 613 JavaThreadState save_state = thread_state(); 614 615 if (save_state == _thread_blocked && is_suspend_equivalent()) { 616 // If the thread's state is _thread_blocked and this blocking 617 // condition is known to be equivalent to a suspend, then we can 618 // consider the thread to be externally suspended. This means that 619 // the code that sets _thread_blocked has been modified to do 620 // self-suspension if the blocking condition releases. We also 621 // used to check for CONDVAR_WAIT here, but that is now covered by 622 // the _thread_blocked with self-suspension check. 623 // 624 // Return true since we wouldn't be here unless there was still an 625 // external suspend request. 626 *bits |= 0x00001000; 627 return true; 628 } else if (save_state == _thread_in_native && frame_anchor()->walkable()) { 629 // Threads running native code will self-suspend on native==>VM/Java 630 // transitions. If its stack is walkable (should always be the case 631 // unless this function is called before the actual java_suspend() 632 // call), then the wait is done. 633 *bits |= 0x00002000; 634 return true; 635 } else if (!called_by_wait && !did_trans_retry && 636 save_state == _thread_in_native_trans && 637 frame_anchor()->walkable()) { 638 // The thread is transitioning from thread_in_native to another 639 // thread state. check_safepoint_and_suspend_for_native_trans() 640 // will force the thread to self-suspend. If it hasn't gotten 641 // there yet we may have caught the thread in-between the native 642 // code check above and the self-suspend. Lucky us. If we were 643 // called by wait_for_ext_suspend_completion(), then it 644 // will be doing the retries so we don't have to. 645 // 646 // Since we use the saved thread state in the if-statement above, 647 // there is a chance that the thread has already transitioned to 648 // _thread_blocked by the time we get here. In that case, we will 649 // make a single unnecessary pass through the logic below. This 650 // doesn't hurt anything since we still do the trans retry. 651 652 *bits |= 0x00004000; 653 654 // Once the thread leaves thread_in_native_trans for another 655 // thread state, we break out of this retry loop. We shouldn't 656 // need this flag to prevent us from getting back here, but 657 // sometimes paranoia is good. 658 did_trans_retry = true; 659 660 // We wait for the thread to transition to a more usable state. 661 for (int i = 1; i <= SuspendRetryCount; i++) { 662 // We used to do an "os::yield_all(i)" call here with the intention 663 // that yielding would increase on each retry. However, the parameter 664 // is ignored on Linux which means the yield didn't scale up. Waiting 665 // on the SR_lock below provides a much more predictable scale up for 666 // the delay. It also provides a simple/direct point to check for any 667 // safepoint requests from the VMThread 668 669 // temporarily drops SR_lock while doing wait with safepoint check 670 // (if we're a JavaThread - the WatcherThread can also call this) 671 // and increase delay with each retry 672 SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay); 673 674 // check the actual thread state instead of what we saved above 675 if (thread_state() != _thread_in_native_trans) { 676 // the thread has transitioned to another thread state so 677 // try all the checks (except this one) one more time. 678 do_trans_retry = true; 679 break; 680 } 681 } // end retry loop 682 683 684 } 685 } while (do_trans_retry); 686 687 *bits |= 0x00000010; 688 return false; 689 } 690 691 // Wait for an external suspend request to complete (or be cancelled). 692 // Returns true if the thread is externally suspended and false otherwise. 693 // 694 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay, 695 uint32_t *bits) { 696 TraceSuspendDebugBits tsdb(this, true /* is_wait */, 697 false /* !called_by_wait */, bits); 698 699 // local flag copies to minimize SR_lock hold time 700 bool is_suspended; 701 bool pending; 702 uint32_t reset_bits; 703 704 // set a marker so is_ext_suspend_completed() knows we are the caller 705 *bits |= 0x00010000; 706 707 // We use reset_bits to reinitialize the bits value at the top of 708 // each retry loop. This allows the caller to make use of any 709 // unused bits for their own marking purposes. 710 reset_bits = *bits; 711 712 { 713 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 714 is_suspended = is_ext_suspend_completed(true /* called_by_wait */, 715 delay, bits); 716 pending = is_external_suspend(); 717 } 718 // must release SR_lock to allow suspension to complete 719 720 if (!pending) { 721 // A cancelled suspend request is the only false return from 722 // is_ext_suspend_completed() that keeps us from entering the 723 // retry loop. 724 *bits |= 0x00020000; 725 return false; 726 } 727 728 if (is_suspended) { 729 *bits |= 0x00040000; 730 return true; 731 } 732 733 for (int i = 1; i <= retries; i++) { 734 *bits = reset_bits; // reinit to only track last retry 735 736 // We used to do an "os::yield_all(i)" call here with the intention 737 // that yielding would increase on each retry. However, the parameter 738 // is ignored on Linux which means the yield didn't scale up. Waiting 739 // on the SR_lock below provides a much more predictable scale up for 740 // the delay. It also provides a simple/direct point to check for any 741 // safepoint requests from the VMThread 742 743 { 744 MutexLocker ml(SR_lock()); 745 // wait with safepoint check (if we're a JavaThread - the WatcherThread 746 // can also call this) and increase delay with each retry 747 SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay); 748 749 is_suspended = is_ext_suspend_completed(true /* called_by_wait */, 750 delay, bits); 751 752 // It is possible for the external suspend request to be cancelled 753 // (by a resume) before the actual suspend operation is completed. 754 // Refresh our local copy to see if we still need to wait. 755 pending = is_external_suspend(); 756 } 757 758 if (!pending) { 759 // A cancelled suspend request is the only false return from 760 // is_ext_suspend_completed() that keeps us from staying in the 761 // retry loop. 762 *bits |= 0x00080000; 763 return false; 764 } 765 766 if (is_suspended) { 767 *bits |= 0x00100000; 768 return true; 769 } 770 } // end retry loop 771 772 // thread did not suspend after all our retries 773 *bits |= 0x00200000; 774 return false; 775 } 776 777 // Called from API entry points which perform stack walking. If the 778 // associated JavaThread is the current thread, then wait_for_suspend 779 // is not used. Otherwise, it determines if we should wait for the 780 // "other" thread to complete external suspension. (NOTE: in future 781 // releases the suspension mechanism should be reimplemented so this 782 // is not necessary.) 783 // 784 bool 785 JavaThread::is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits) { 786 if (this != JavaThread::current()) { 787 // "other" threads require special handling. 788 if (wait_for_suspend) { 789 // We are allowed to wait for the external suspend to complete 790 // so give the other thread a chance to get suspended. 791 if (!wait_for_ext_suspend_completion(SuspendRetryCount, 792 SuspendRetryDelay, bits)) { 793 // Didn't make it so let the caller know. 794 return false; 795 } 796 } 797 // We aren't allowed to wait for the external suspend to complete 798 // so if the other thread isn't externally suspended we need to 799 // let the caller know. 800 else if (!is_ext_suspend_completed_with_lock(bits)) { 801 return false; 802 } 803 } 804 805 return true; 806 } 807 808 #ifndef PRODUCT 809 void JavaThread::record_jump(address target, address instr, const char* file, 810 int line) { 811 812 // This should not need to be atomic as the only way for simultaneous 813 // updates is via interrupts. Even then this should be rare or non-existent 814 // and we don't care that much anyway. 815 816 int index = _jmp_ring_index; 817 _jmp_ring_index = (index + 1) & (jump_ring_buffer_size - 1); 818 _jmp_ring[index]._target = (intptr_t) target; 819 _jmp_ring[index]._instruction = (intptr_t) instr; 820 _jmp_ring[index]._file = file; 821 _jmp_ring[index]._line = line; 822 } 823 #endif // PRODUCT 824 825 void Thread::interrupt(Thread* thread) { 826 debug_only(check_for_dangling_thread_pointer(thread);) 827 os::interrupt(thread); 828 } 829 830 bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) { 831 debug_only(check_for_dangling_thread_pointer(thread);) 832 // Note: If clear_interrupted==false, this simply fetches and 833 // returns the value of the field osthread()->interrupted(). 834 return os::is_interrupted(thread, clear_interrupted); 835 } 836 837 838 // GC Support 839 bool Thread::claim_oops_do_par_case(int strong_roots_parity) { 840 int thread_parity = _oops_do_parity; 841 if (thread_parity != strong_roots_parity) { 842 jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity); 843 if (res == thread_parity) { 844 return true; 845 } else { 846 guarantee(res == strong_roots_parity, "Or else what?"); 847 return false; 848 } 849 } 850 return false; 851 } 852 853 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 854 active_handles()->oops_do(f); 855 // Do oop for ThreadShadow 856 f->do_oop((oop*)&_pending_exception); 857 handle_area()->oops_do(f); 858 859 if (MonitorInUseLists) { 860 // When using thread local monitor lists, we scan them here, 861 // and the remaining global monitors in ObjectSynchronizer::oops_do(). 862 ObjectSynchronizer::thread_local_used_oops_do(this, f); 863 } 864 } 865 866 void Thread::metadata_handles_do(void f(Metadata*)) { 867 // Only walk the Handles in Thread. 868 if (metadata_handles() != NULL) { 869 for (int i = 0; i< metadata_handles()->length(); i++) { 870 f(metadata_handles()->at(i)); 871 } 872 } 873 } 874 875 void Thread::print_on(outputStream* st, bool print_extended_info) const { 876 // get_priority assumes osthread initialized 877 if (osthread() != NULL) { 878 int os_prio; 879 if (os::get_native_priority(this, &os_prio) == OS_OK) { 880 st->print("os_prio=%d ", os_prio); 881 } 882 883 st->print("cpu=%.2fms ", 884 os::thread_cpu_time(const_cast<Thread*>(this), true) / 1000000.0 885 ); 886 st->print("elapsed=%.2fs ", 887 _statistical_info.getElapsedTime() / 1000.0 888 ); 889 if (is_Java_thread() && (PrintExtendedThreadInfo || print_extended_info)) { 890 size_t allocated_bytes = (size_t) const_cast<Thread*>(this)->cooked_allocated_bytes(); 891 st->print("allocated=" SIZE_FORMAT "%s ", 892 byte_size_in_proper_unit(allocated_bytes), 893 proper_unit_for_byte_size(allocated_bytes) 894 ); 895 st->print("defined_classes=" INT64_FORMAT " ", _statistical_info.getDefineClassCount()); 896 } 897 898 st->print("tid=" INTPTR_FORMAT " ", p2i(this)); 899 osthread()->print_on(st); 900 } 901 ThreadsSMRSupport::print_info_on(this, st); 902 st->print(" "); 903 debug_only(if (WizardMode) print_owned_locks_on(st);) 904 } 905 906 // Thread::print_on_error() is called by fatal error handler. Don't use 907 // any lock or allocate memory. 908 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const { 909 assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates"); 910 911 if (is_VM_thread()) { st->print("VMThread"); } 912 else if (is_GC_task_thread()) { st->print("GCTaskThread"); } 913 else if (is_Watcher_thread()) { st->print("WatcherThread"); } 914 else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); } 915 else { st->print("Thread"); } 916 917 if (is_Named_thread()) { 918 st->print(" \"%s\"", name()); 919 } 920 921 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]", 922 p2i(stack_end()), p2i(stack_base())); 923 924 if (osthread()) { 925 st->print(" [id=%d]", osthread()->thread_id()); 926 } 927 928 ThreadsSMRSupport::print_info_on(this, st); 929 } 930 931 void Thread::print_value_on(outputStream* st) const { 932 if (is_Named_thread()) { 933 st->print(" \"%s\" ", name()); 934 } 935 st->print(INTPTR_FORMAT, p2i(this)); // print address 936 } 937 938 #ifdef ASSERT 939 void Thread::print_owned_locks_on(outputStream* st) const { 940 Monitor *cur = _owned_locks; 941 if (cur == NULL) { 942 st->print(" (no locks) "); 943 } else { 944 st->print_cr(" Locks owned:"); 945 while (cur) { 946 cur->print_on(st); 947 cur = cur->next(); 948 } 949 } 950 } 951 952 static int ref_use_count = 0; 953 954 bool Thread::owns_locks_but_compiled_lock() const { 955 for (Monitor *cur = _owned_locks; cur; cur = cur->next()) { 956 if (cur != Compile_lock) return true; 957 } 958 return false; 959 } 960 961 962 #endif 963 964 #ifndef PRODUCT 965 966 // The flag: potential_vm_operation notifies if this particular safepoint state could potentially 967 // invoke the vm-thread (e.g., an oop allocation). In that case, we also have to make sure that 968 // no locks which allow_vm_block's are held 969 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) { 970 // Check if current thread is allowed to block at a safepoint 971 if (!(_allow_safepoint_count == 0)) { 972 fatal("Possible safepoint reached by thread that does not allow it"); 973 } 974 if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) { 975 fatal("LEAF method calling lock?"); 976 } 977 978 #ifdef ASSERT 979 if (potential_vm_operation && is_Java_thread() 980 && !Universe::is_bootstrapping()) { 981 // Make sure we do not hold any locks that the VM thread also uses. 982 // This could potentially lead to deadlocks 983 for (Monitor *cur = _owned_locks; cur; cur = cur->next()) { 984 // Threads_lock is special, since the safepoint synchronization will not start before this is 985 // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock, 986 // since it is used to transfer control between JavaThreads and the VMThread 987 // Do not *exclude* any locks unless you are absolutely sure it is correct. Ask someone else first! 988 if ((cur->allow_vm_block() && 989 cur != Threads_lock && 990 cur != Compile_lock && // Temporary: should not be necessary when we get separate compilation 991 cur != VMOperationRequest_lock && 992 cur != VMOperationQueue_lock) || 993 cur->rank() == Mutex::special) { 994 fatal("Thread holding lock at safepoint that vm can block on: %s", cur->name()); 995 } 996 } 997 } 998 999 if (GCALotAtAllSafepoints) { 1000 // We could enter a safepoint here and thus have a gc 1001 InterfaceSupport::check_gc_alot(); 1002 } 1003 #endif 1004 } 1005 #endif 1006 1007 bool Thread::is_in_stack(address adr) const { 1008 assert(Thread::current() == this, "is_in_stack can only be called from current thread"); 1009 address end = os::current_stack_pointer(); 1010 // Allow non Java threads to call this without stack_base 1011 if (_stack_base == NULL) return true; 1012 if (stack_base() >= adr && adr >= end) return true; 1013 1014 return false; 1015 } 1016 1017 bool Thread::is_in_usable_stack(address adr) const { 1018 size_t stack_guard_size = os::uses_stack_guard_pages() ? JavaThread::stack_guard_zone_size() : 0; 1019 size_t usable_stack_size = _stack_size - stack_guard_size; 1020 1021 return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size)); 1022 } 1023 1024 1025 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter 1026 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being 1027 // used for compilation in the future. If that change is made, the need for these methods 1028 // should be revisited, and they should be removed if possible. 1029 1030 bool Thread::is_lock_owned(address adr) const { 1031 return on_local_stack(adr); 1032 } 1033 1034 bool Thread::set_as_starting_thread() { 1035 // NOTE: this must be called inside the main thread. 1036 return os::create_main_thread((JavaThread*)this); 1037 } 1038 1039 static void initialize_class(Symbol* class_name, TRAPS) { 1040 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK); 1041 InstanceKlass::cast(klass)->initialize(CHECK); 1042 } 1043 1044 1045 // Creates the initial ThreadGroup 1046 static Handle create_initial_thread_group(TRAPS) { 1047 Handle system_instance = JavaCalls::construct_new_instance( 1048 SystemDictionary::ThreadGroup_klass(), 1049 vmSymbols::void_method_signature(), 1050 CHECK_NH); 1051 Universe::set_system_thread_group(system_instance()); 1052 1053 Handle string = java_lang_String::create_from_str("main", CHECK_NH); 1054 Handle main_instance = JavaCalls::construct_new_instance( 1055 SystemDictionary::ThreadGroup_klass(), 1056 vmSymbols::threadgroup_string_void_signature(), 1057 system_instance, 1058 string, 1059 CHECK_NH); 1060 return main_instance; 1061 } 1062 1063 // Creates the initial Thread 1064 static oop create_initial_thread(Handle thread_group, JavaThread* thread, 1065 TRAPS) { 1066 InstanceKlass* ik = SystemDictionary::Thread_klass(); 1067 assert(ik->is_initialized(), "must be"); 1068 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK_NULL); 1069 1070 // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread 1071 // constructor calls Thread.current(), which must be set here for the 1072 // initial thread. 1073 java_lang_Thread::set_thread(thread_oop(), thread); 1074 java_lang_Thread::set_priority(thread_oop(), NormPriority); 1075 thread->set_threadObj(thread_oop()); 1076 1077 Handle string = java_lang_String::create_from_str("main", CHECK_NULL); 1078 1079 JavaValue result(T_VOID); 1080 JavaCalls::call_special(&result, thread_oop, 1081 ik, 1082 vmSymbols::object_initializer_name(), 1083 vmSymbols::threadgroup_string_void_signature(), 1084 thread_group, 1085 string, 1086 CHECK_NULL); 1087 return thread_oop(); 1088 } 1089 1090 char java_runtime_name[128] = ""; 1091 char java_runtime_version[128] = ""; 1092 1093 // extract the JRE name from java.lang.VersionProps.java_runtime_name 1094 static const char* get_java_runtime_name(TRAPS) { 1095 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(), 1096 Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1097 fieldDescriptor fd; 1098 bool found = k != NULL && 1099 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(), 1100 vmSymbols::string_signature(), &fd); 1101 if (found) { 1102 oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1103 if (name_oop == NULL) { 1104 return NULL; 1105 } 1106 const char* name = java_lang_String::as_utf8_string(name_oop, 1107 java_runtime_name, 1108 sizeof(java_runtime_name)); 1109 return name; 1110 } else { 1111 return NULL; 1112 } 1113 } 1114 1115 // extract the JRE version from java.lang.VersionProps.java_runtime_version 1116 static const char* get_java_runtime_version(TRAPS) { 1117 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(), 1118 Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1119 fieldDescriptor fd; 1120 bool found = k != NULL && 1121 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(), 1122 vmSymbols::string_signature(), &fd); 1123 if (found) { 1124 oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1125 if (name_oop == NULL) { 1126 return NULL; 1127 } 1128 const char* name = java_lang_String::as_utf8_string(name_oop, 1129 java_runtime_version, 1130 sizeof(java_runtime_version)); 1131 return name; 1132 } else { 1133 return NULL; 1134 } 1135 } 1136 1137 // General purpose hook into Java code, run once when the VM is initialized. 1138 // The Java library method itself may be changed independently from the VM. 1139 static void call_postVMInitHook(TRAPS) { 1140 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD); 1141 if (klass != NULL) { 1142 JavaValue result(T_VOID); 1143 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(), 1144 vmSymbols::void_method_signature(), 1145 CHECK); 1146 } 1147 } 1148 1149 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name, 1150 bool daemon, TRAPS) { 1151 assert(thread_group.not_null(), "thread group should be specified"); 1152 assert(threadObj() == NULL, "should only create Java thread object once"); 1153 1154 InstanceKlass* ik = SystemDictionary::Thread_klass(); 1155 assert(ik->is_initialized(), "must be"); 1156 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK); 1157 1158 // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon. 1159 // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread 1160 // constructor calls Thread.current(), which must be set here. 1161 java_lang_Thread::set_thread(thread_oop(), this); 1162 java_lang_Thread::set_priority(thread_oop(), NormPriority); 1163 set_threadObj(thread_oop()); 1164 1165 JavaValue result(T_VOID); 1166 if (thread_name != NULL) { 1167 Handle name = java_lang_String::create_from_str(thread_name, CHECK); 1168 // Thread gets assigned specified name and null target 1169 JavaCalls::call_special(&result, 1170 thread_oop, 1171 ik, 1172 vmSymbols::object_initializer_name(), 1173 vmSymbols::threadgroup_string_void_signature(), 1174 thread_group, 1175 name, 1176 THREAD); 1177 } else { 1178 // Thread gets assigned name "Thread-nnn" and null target 1179 // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument) 1180 JavaCalls::call_special(&result, 1181 thread_oop, 1182 ik, 1183 vmSymbols::object_initializer_name(), 1184 vmSymbols::threadgroup_runnable_void_signature(), 1185 thread_group, 1186 Handle(), 1187 THREAD); 1188 } 1189 1190 1191 if (daemon) { 1192 java_lang_Thread::set_daemon(thread_oop()); 1193 } 1194 1195 if (HAS_PENDING_EXCEPTION) { 1196 return; 1197 } 1198 1199 Klass* group = SystemDictionary::ThreadGroup_klass(); 1200 Handle threadObj(THREAD, this->threadObj()); 1201 1202 JavaCalls::call_special(&result, 1203 thread_group, 1204 group, 1205 vmSymbols::add_method_name(), 1206 vmSymbols::thread_void_signature(), 1207 threadObj, // Arg 1 1208 THREAD); 1209 } 1210 1211 // NamedThread -- non-JavaThread subclasses with multiple 1212 // uniquely named instances should derive from this. 1213 NamedThread::NamedThread() : Thread() { 1214 _name = NULL; 1215 _processed_thread = NULL; 1216 _gc_id = GCId::undefined(); 1217 } 1218 1219 NamedThread::~NamedThread() { 1220 if (_name != NULL) { 1221 FREE_C_HEAP_ARRAY(char, _name); 1222 _name = NULL; 1223 } 1224 } 1225 1226 void NamedThread::set_name(const char* format, ...) { 1227 guarantee(_name == NULL, "Only get to set name once."); 1228 _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread); 1229 guarantee(_name != NULL, "alloc failure"); 1230 va_list ap; 1231 va_start(ap, format); 1232 jio_vsnprintf(_name, max_name_len, format, ap); 1233 va_end(ap); 1234 } 1235 1236 void NamedThread::initialize_named_thread() { 1237 set_native_thread_name(name()); 1238 } 1239 1240 void NamedThread::print_on(outputStream* st) const { 1241 st->print("\"%s\" ", name()); 1242 Thread::print_on(st); 1243 st->cr(); 1244 } 1245 1246 1247 // ======= WatcherThread ======== 1248 1249 // The watcher thread exists to simulate timer interrupts. It should 1250 // be replaced by an abstraction over whatever native support for 1251 // timer interrupts exists on the platform. 1252 1253 WatcherThread* WatcherThread::_watcher_thread = NULL; 1254 bool WatcherThread::_startable = false; 1255 volatile bool WatcherThread::_should_terminate = false; 1256 1257 WatcherThread::WatcherThread() : Thread() { 1258 assert(watcher_thread() == NULL, "we can only allocate one WatcherThread"); 1259 if (os::create_thread(this, os::watcher_thread)) { 1260 _watcher_thread = this; 1261 1262 // Set the watcher thread to the highest OS priority which should not be 1263 // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY 1264 // is created. The only normal thread using this priority is the reference 1265 // handler thread, which runs for very short intervals only. 1266 // If the VMThread's priority is not lower than the WatcherThread profiling 1267 // will be inaccurate. 1268 os::set_priority(this, MaxPriority); 1269 if (!DisableStartThread) { 1270 os::start_thread(this); 1271 } 1272 } 1273 } 1274 1275 int WatcherThread::sleep() const { 1276 // The WatcherThread does not participate in the safepoint protocol 1277 // for the PeriodicTask_lock because it is not a JavaThread. 1278 MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag); 1279 1280 if (_should_terminate) { 1281 // check for termination before we do any housekeeping or wait 1282 return 0; // we did not sleep. 1283 } 1284 1285 // remaining will be zero if there are no tasks, 1286 // causing the WatcherThread to sleep until a task is 1287 // enrolled 1288 int remaining = PeriodicTask::time_to_wait(); 1289 int time_slept = 0; 1290 1291 // we expect this to timeout - we only ever get unparked when 1292 // we should terminate or when a new task has been enrolled 1293 OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */); 1294 1295 jlong time_before_loop = os::javaTimeNanos(); 1296 1297 while (true) { 1298 bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag, 1299 remaining); 1300 jlong now = os::javaTimeNanos(); 1301 1302 if (remaining == 0) { 1303 // if we didn't have any tasks we could have waited for a long time 1304 // consider the time_slept zero and reset time_before_loop 1305 time_slept = 0; 1306 time_before_loop = now; 1307 } else { 1308 // need to recalculate since we might have new tasks in _tasks 1309 time_slept = (int) ((now - time_before_loop) / 1000000); 1310 } 1311 1312 // Change to task list or spurious wakeup of some kind 1313 if (timedout || _should_terminate) { 1314 break; 1315 } 1316 1317 remaining = PeriodicTask::time_to_wait(); 1318 if (remaining == 0) { 1319 // Last task was just disenrolled so loop around and wait until 1320 // another task gets enrolled 1321 continue; 1322 } 1323 1324 remaining -= time_slept; 1325 if (remaining <= 0) { 1326 break; 1327 } 1328 } 1329 1330 return time_slept; 1331 } 1332 1333 void WatcherThread::run() { 1334 assert(this == watcher_thread(), "just checking"); 1335 1336 this->record_stack_base_and_size(); 1337 this->set_native_thread_name(this->name()); 1338 this->set_active_handles(JNIHandleBlock::allocate_block()); 1339 while (true) { 1340 assert(watcher_thread() == Thread::current(), "thread consistency check"); 1341 assert(watcher_thread() == this, "thread consistency check"); 1342 1343 // Calculate how long it'll be until the next PeriodicTask work 1344 // should be done, and sleep that amount of time. 1345 int time_waited = sleep(); 1346 1347 if (VMError::is_error_reported()) { 1348 // A fatal error has happened, the error handler(VMError::report_and_die) 1349 // should abort JVM after creating an error log file. However in some 1350 // rare cases, the error handler itself might deadlock. Here periodically 1351 // check for error reporting timeouts, and if it happens, just proceed to 1352 // abort the VM. 1353 1354 // This code is in WatcherThread because WatcherThread wakes up 1355 // periodically so the fatal error handler doesn't need to do anything; 1356 // also because the WatcherThread is less likely to crash than other 1357 // threads. 1358 1359 for (;;) { 1360 // Note: we use naked sleep in this loop because we want to avoid using 1361 // any kind of VM infrastructure which may be broken at this point. 1362 if (VMError::check_timeout()) { 1363 // We hit error reporting timeout. Error reporting was interrupted and 1364 // will be wrapping things up now (closing files etc). Give it some more 1365 // time, then quit the VM. 1366 os::naked_short_sleep(200); 1367 // Print a message to stderr. 1368 fdStream err(defaultStream::output_fd()); 1369 err.print_raw_cr("# [ timer expired, abort... ]"); 1370 // skip atexit/vm_exit/vm_abort hooks 1371 os::die(); 1372 } 1373 1374 // Wait a second, then recheck for timeout. 1375 os::naked_short_sleep(999); 1376 } 1377 } 1378 1379 if (_should_terminate) { 1380 // check for termination before posting the next tick 1381 break; 1382 } 1383 1384 PeriodicTask::real_time_tick(time_waited); 1385 } 1386 1387 // Signal that it is terminated 1388 { 1389 MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag); 1390 _watcher_thread = NULL; 1391 Terminator_lock->notify(); 1392 } 1393 } 1394 1395 void WatcherThread::start() { 1396 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1397 1398 if (watcher_thread() == NULL && _startable) { 1399 _should_terminate = false; 1400 // Create the single instance of WatcherThread 1401 new WatcherThread(); 1402 } 1403 } 1404 1405 void WatcherThread::make_startable() { 1406 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1407 _startable = true; 1408 } 1409 1410 void WatcherThread::stop() { 1411 { 1412 // Follow normal safepoint aware lock enter protocol since the 1413 // WatcherThread is stopped by another JavaThread. 1414 MutexLocker ml(PeriodicTask_lock); 1415 _should_terminate = true; 1416 1417 WatcherThread* watcher = watcher_thread(); 1418 if (watcher != NULL) { 1419 // unpark the WatcherThread so it can see that it should terminate 1420 watcher->unpark(); 1421 } 1422 } 1423 1424 MutexLocker mu(Terminator_lock); 1425 1426 while (watcher_thread() != NULL) { 1427 // This wait should make safepoint checks, wait without a timeout, 1428 // and wait as a suspend-equivalent condition. 1429 Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0, 1430 Mutex::_as_suspend_equivalent_flag); 1431 } 1432 } 1433 1434 void WatcherThread::unpark() { 1435 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1436 PeriodicTask_lock->notify(); 1437 } 1438 1439 void WatcherThread::print_on(outputStream* st) const { 1440 st->print("\"%s\" ", name()); 1441 Thread::print_on(st); 1442 st->cr(); 1443 } 1444 1445 // ======= JavaThread ======== 1446 1447 #if INCLUDE_JVMCI 1448 1449 jlong* JavaThread::_jvmci_old_thread_counters; 1450 1451 bool jvmci_counters_include(JavaThread* thread) { 1452 return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread(); 1453 } 1454 1455 void JavaThread::collect_counters(typeArrayOop array) { 1456 if (JVMCICounterSize > 0) { 1457 JavaThreadIteratorWithHandle jtiwh; 1458 for (int i = 0; i < array->length(); i++) { 1459 array->long_at_put(i, _jvmci_old_thread_counters[i]); 1460 } 1461 for (; JavaThread *tp = jtiwh.next(); ) { 1462 if (jvmci_counters_include(tp)) { 1463 for (int i = 0; i < array->length(); i++) { 1464 array->long_at_put(i, array->long_at(i) + tp->_jvmci_counters[i]); 1465 } 1466 } 1467 } 1468 } 1469 } 1470 1471 #endif // INCLUDE_JVMCI 1472 1473 // A JavaThread is a normal Java thread 1474 1475 void JavaThread::initialize() { 1476 // Initialize fields 1477 1478 set_saved_exception_pc(NULL); 1479 set_threadObj(NULL); 1480 _anchor.clear(); 1481 set_entry_point(NULL); 1482 set_jni_functions(jni_functions()); 1483 set_callee_target(NULL); 1484 set_vm_result(NULL); 1485 set_vm_result_2(NULL); 1486 set_vframe_array_head(NULL); 1487 set_vframe_array_last(NULL); 1488 set_deferred_locals(NULL); 1489 set_deopt_mark(NULL); 1490 set_deopt_compiled_method(NULL); 1491 clear_must_deopt_id(); 1492 set_monitor_chunks(NULL); 1493 set_next(NULL); 1494 _on_thread_list = false; 1495 set_thread_state(_thread_new); 1496 _terminated = _not_terminated; 1497 _privileged_stack_top = NULL; 1498 _array_for_gc = NULL; 1499 _suspend_equivalent = false; 1500 _in_deopt_handler = 0; 1501 _doing_unsafe_access = false; 1502 _stack_guard_state = stack_guard_unused; 1503 #if INCLUDE_JVMCI 1504 _pending_monitorenter = false; 1505 _pending_deoptimization = -1; 1506 _pending_failed_speculation = 0; 1507 _pending_transfer_to_interpreter = false; 1508 _adjusting_comp_level = false; 1509 _jvmci._alternate_call_target = NULL; 1510 assert(_jvmci._implicit_exception_pc == NULL, "must be"); 1511 if (JVMCICounterSize > 0) { 1512 _jvmci_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal); 1513 memset(_jvmci_counters, 0, sizeof(jlong) * JVMCICounterSize); 1514 } else { 1515 _jvmci_counters = NULL; 1516 } 1517 #endif // INCLUDE_JVMCI 1518 _reserved_stack_activation = NULL; // stack base not known yet 1519 (void)const_cast<oop&>(_exception_oop = oop(NULL)); 1520 _exception_pc = 0; 1521 _exception_handler_pc = 0; 1522 _is_method_handle_return = 0; 1523 _jvmti_thread_state= NULL; 1524 _should_post_on_exceptions_flag = JNI_FALSE; 1525 _jvmti_get_loaded_classes_closure = NULL; 1526 _interp_only_mode = 0; 1527 _special_runtime_exit_condition = _no_async_condition; 1528 _pending_async_exception = NULL; 1529 _thread_stat = NULL; 1530 _thread_stat = new ThreadStatistics(); 1531 _blocked_on_compilation = false; 1532 _jni_active_critical = 0; 1533 _pending_jni_exception_check_fn = NULL; 1534 _do_not_unlock_if_synchronized = false; 1535 _cached_monitor_info = NULL; 1536 _parker = Parker::Allocate(this); 1537 1538 #ifndef PRODUCT 1539 _jmp_ring_index = 0; 1540 for (int ji = 0; ji < jump_ring_buffer_size; ji++) { 1541 record_jump(NULL, NULL, NULL, 0); 1542 } 1543 #endif // PRODUCT 1544 1545 // Setup safepoint state info for this thread 1546 ThreadSafepointState::create(this); 1547 1548 debug_only(_java_call_counter = 0); 1549 1550 // JVMTI PopFrame support 1551 _popframe_condition = popframe_inactive; 1552 _popframe_preserved_args = NULL; 1553 _popframe_preserved_args_size = 0; 1554 _frames_to_pop_failed_realloc = 0; 1555 1556 if (SafepointMechanism::uses_thread_local_poll()) { 1557 SafepointMechanism::initialize_header(this); 1558 } 1559 1560 pd_initialize(); 1561 } 1562 1563 JavaThread::JavaThread(bool is_attaching_via_jni) : 1564 Thread() { 1565 initialize(); 1566 if (is_attaching_via_jni) { 1567 _jni_attach_state = _attaching_via_jni; 1568 } else { 1569 _jni_attach_state = _not_attaching_via_jni; 1570 } 1571 assert(deferred_card_mark().is_empty(), "Default MemRegion ctor"); 1572 } 1573 1574 bool JavaThread::reguard_stack(address cur_sp) { 1575 if (_stack_guard_state != stack_guard_yellow_reserved_disabled 1576 && _stack_guard_state != stack_guard_reserved_disabled) { 1577 return true; // Stack already guarded or guard pages not needed. 1578 } 1579 1580 if (register_stack_overflow()) { 1581 // For those architectures which have separate register and 1582 // memory stacks, we must check the register stack to see if 1583 // it has overflowed. 1584 return false; 1585 } 1586 1587 // Java code never executes within the yellow zone: the latter is only 1588 // there to provoke an exception during stack banging. If java code 1589 // is executing there, either StackShadowPages should be larger, or 1590 // some exception code in c1, c2 or the interpreter isn't unwinding 1591 // when it should. 1592 guarantee(cur_sp > stack_reserved_zone_base(), 1593 "not enough space to reguard - increase StackShadowPages"); 1594 if (_stack_guard_state == stack_guard_yellow_reserved_disabled) { 1595 enable_stack_yellow_reserved_zone(); 1596 if (reserved_stack_activation() != stack_base()) { 1597 set_reserved_stack_activation(stack_base()); 1598 } 1599 } else if (_stack_guard_state == stack_guard_reserved_disabled) { 1600 set_reserved_stack_activation(stack_base()); 1601 enable_stack_reserved_zone(); 1602 } 1603 return true; 1604 } 1605 1606 bool JavaThread::reguard_stack(void) { 1607 return reguard_stack(os::current_stack_pointer()); 1608 } 1609 1610 1611 void JavaThread::block_if_vm_exited() { 1612 if (_terminated == _vm_exited) { 1613 // _vm_exited is set at safepoint, and Threads_lock is never released 1614 // we will block here forever 1615 Threads_lock->lock_without_safepoint_check(); 1616 ShouldNotReachHere(); 1617 } 1618 } 1619 1620 1621 // Remove this ifdef when C1 is ported to the compiler interface. 1622 static void compiler_thread_entry(JavaThread* thread, TRAPS); 1623 static void sweeper_thread_entry(JavaThread* thread, TRAPS); 1624 1625 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : 1626 Thread() { 1627 initialize(); 1628 _jni_attach_state = _not_attaching_via_jni; 1629 set_entry_point(entry_point); 1630 // Create the native thread itself. 1631 // %note runtime_23 1632 os::ThreadType thr_type = os::java_thread; 1633 thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread : 1634 os::java_thread; 1635 os::create_thread(this, thr_type, stack_sz); 1636 // The _osthread may be NULL here because we ran out of memory (too many threads active). 1637 // We need to throw and OutOfMemoryError - however we cannot do this here because the caller 1638 // may hold a lock and all locks must be unlocked before throwing the exception (throwing 1639 // the exception consists of creating the exception object & initializing it, initialization 1640 // will leave the VM via a JavaCall and then all locks must be unlocked). 1641 // 1642 // The thread is still suspended when we reach here. Thread must be explicit started 1643 // by creator! Furthermore, the thread must also explicitly be added to the Threads list 1644 // by calling Threads:add. The reason why this is not done here, is because the thread 1645 // object must be fully initialized (take a look at JVM_Start) 1646 } 1647 1648 JavaThread::~JavaThread() { 1649 1650 // JSR166 -- return the parker to the free list 1651 Parker::Release(_parker); 1652 _parker = NULL; 1653 1654 // Free any remaining previous UnrollBlock 1655 vframeArray* old_array = vframe_array_last(); 1656 1657 if (old_array != NULL) { 1658 Deoptimization::UnrollBlock* old_info = old_array->unroll_block(); 1659 old_array->set_unroll_block(NULL); 1660 delete old_info; 1661 delete old_array; 1662 } 1663 1664 GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals(); 1665 if (deferred != NULL) { 1666 // This can only happen if thread is destroyed before deoptimization occurs. 1667 assert(deferred->length() != 0, "empty array!"); 1668 do { 1669 jvmtiDeferredLocalVariableSet* dlv = deferred->at(0); 1670 deferred->remove_at(0); 1671 // individual jvmtiDeferredLocalVariableSet are CHeapObj's 1672 delete dlv; 1673 } while (deferred->length() != 0); 1674 delete deferred; 1675 } 1676 1677 // All Java related clean up happens in exit 1678 ThreadSafepointState::destroy(this); 1679 if (_thread_stat != NULL) delete _thread_stat; 1680 1681 #if INCLUDE_JVMCI 1682 if (JVMCICounterSize > 0) { 1683 if (jvmci_counters_include(this)) { 1684 for (int i = 0; i < JVMCICounterSize; i++) { 1685 _jvmci_old_thread_counters[i] += _jvmci_counters[i]; 1686 } 1687 } 1688 FREE_C_HEAP_ARRAY(jlong, _jvmci_counters); 1689 } 1690 #endif // INCLUDE_JVMCI 1691 } 1692 1693 1694 // The first routine called by a new Java thread 1695 void JavaThread::run() { 1696 // initialize thread-local alloc buffer related fields 1697 this->initialize_tlab(); 1698 1699 // used to test validity of stack trace backs 1700 this->record_base_of_stack_pointer(); 1701 1702 // Record real stack base and size. 1703 this->record_stack_base_and_size(); 1704 1705 this->create_stack_guard_pages(); 1706 1707 this->cache_global_variables(); 1708 1709 // Thread is now sufficient initialized to be handled by the safepoint code as being 1710 // in the VM. Change thread state from _thread_new to _thread_in_vm 1711 ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm); 1712 1713 assert(JavaThread::current() == this, "sanity check"); 1714 assert(!Thread::current()->owns_locks(), "sanity check"); 1715 1716 DTRACE_THREAD_PROBE(start, this); 1717 1718 // This operation might block. We call that after all safepoint checks for a new thread has 1719 // been completed. 1720 this->set_active_handles(JNIHandleBlock::allocate_block()); 1721 1722 if (JvmtiExport::should_post_thread_life()) { 1723 JvmtiExport::post_thread_start(this); 1724 } 1725 1726 EventThreadStart event; 1727 if (event.should_commit()) { 1728 event.set_thread(JFR_THREAD_ID(this)); 1729 event.commit(); 1730 } 1731 1732 // We call another function to do the rest so we are sure that the stack addresses used 1733 // from there will be lower than the stack base just computed 1734 thread_main_inner(); 1735 1736 // Note, thread is no longer valid at this point! 1737 } 1738 1739 1740 void JavaThread::thread_main_inner() { 1741 assert(JavaThread::current() == this, "sanity check"); 1742 assert(this->threadObj() != NULL, "just checking"); 1743 1744 // Execute thread entry point unless this thread has a pending exception 1745 // or has been stopped before starting. 1746 // Note: Due to JVM_StopThread we can have pending exceptions already! 1747 if (!this->has_pending_exception() && 1748 !java_lang_Thread::is_stillborn(this->threadObj())) { 1749 { 1750 ResourceMark rm(this); 1751 this->set_native_thread_name(this->get_thread_name()); 1752 } 1753 HandleMark hm(this); 1754 this->entry_point()(this, this); 1755 } 1756 1757 DTRACE_THREAD_PROBE(stop, this); 1758 1759 this->exit(false); 1760 this->smr_delete(); 1761 } 1762 1763 1764 static void ensure_join(JavaThread* thread) { 1765 // We do not need to grab the Threads_lock, since we are operating on ourself. 1766 Handle threadObj(thread, thread->threadObj()); 1767 assert(threadObj.not_null(), "java thread object must exist"); 1768 ObjectLocker lock(threadObj, thread); 1769 // Ignore pending exception (ThreadDeath), since we are exiting anyway 1770 thread->clear_pending_exception(); 1771 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED. 1772 java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED); 1773 // Clear the native thread instance - this makes isAlive return false and allows the join() 1774 // to complete once we've done the notify_all below 1775 java_lang_Thread::set_thread(threadObj(), NULL); 1776 lock.notify_all(thread); 1777 // Ignore pending exception (ThreadDeath), since we are exiting anyway 1778 thread->clear_pending_exception(); 1779 } 1780 1781 1782 // For any new cleanup additions, please check to see if they need to be applied to 1783 // cleanup_failed_attach_current_thread as well. 1784 void JavaThread::exit(bool destroy_vm, ExitType exit_type) { 1785 assert(this == JavaThread::current(), "thread consistency check"); 1786 1787 elapsedTimer _timer_exit_phase1; 1788 elapsedTimer _timer_exit_phase2; 1789 elapsedTimer _timer_exit_phase3; 1790 elapsedTimer _timer_exit_phase4; 1791 1792 if (log_is_enabled(Debug, os, thread, timer)) { 1793 _timer_exit_phase1.start(); 1794 } 1795 1796 HandleMark hm(this); 1797 Handle uncaught_exception(this, this->pending_exception()); 1798 this->clear_pending_exception(); 1799 Handle threadObj(this, this->threadObj()); 1800 assert(threadObj.not_null(), "Java thread object should be created"); 1801 1802 // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place 1803 { 1804 EXCEPTION_MARK; 1805 1806 CLEAR_PENDING_EXCEPTION; 1807 } 1808 if (!destroy_vm) { 1809 if (uncaught_exception.not_null()) { 1810 EXCEPTION_MARK; 1811 // Call method Thread.dispatchUncaughtException(). 1812 Klass* thread_klass = SystemDictionary::Thread_klass(); 1813 JavaValue result(T_VOID); 1814 JavaCalls::call_virtual(&result, 1815 threadObj, thread_klass, 1816 vmSymbols::dispatchUncaughtException_name(), 1817 vmSymbols::throwable_void_signature(), 1818 uncaught_exception, 1819 THREAD); 1820 if (HAS_PENDING_EXCEPTION) { 1821 ResourceMark rm(this); 1822 jio_fprintf(defaultStream::error_stream(), 1823 "\nException: %s thrown from the UncaughtExceptionHandler" 1824 " in thread \"%s\"\n", 1825 pending_exception()->klass()->external_name(), 1826 get_thread_name()); 1827 CLEAR_PENDING_EXCEPTION; 1828 } 1829 } 1830 1831 // Called before the java thread exit since we want to read info 1832 // from java_lang_Thread object 1833 EventThreadEnd event; 1834 if (event.should_commit()) { 1835 event.set_thread(JFR_THREAD_ID(this)); 1836 event.commit(); 1837 } 1838 1839 // Call after last event on thread 1840 JFR_ONLY(Jfr::on_thread_exit(this);) 1841 1842 // Call Thread.exit(). We try 3 times in case we got another Thread.stop during 1843 // the execution of the method. If that is not enough, then we don't really care. Thread.stop 1844 // is deprecated anyhow. 1845 if (!is_Compiler_thread()) { 1846 int count = 3; 1847 while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) { 1848 EXCEPTION_MARK; 1849 JavaValue result(T_VOID); 1850 Klass* thread_klass = SystemDictionary::Thread_klass(); 1851 JavaCalls::call_virtual(&result, 1852 threadObj, thread_klass, 1853 vmSymbols::exit_method_name(), 1854 vmSymbols::void_method_signature(), 1855 THREAD); 1856 CLEAR_PENDING_EXCEPTION; 1857 } 1858 } 1859 // notify JVMTI 1860 if (JvmtiExport::should_post_thread_life()) { 1861 JvmtiExport::post_thread_end(this); 1862 } 1863 1864 // We have notified the agents that we are exiting, before we go on, 1865 // we must check for a pending external suspend request and honor it 1866 // in order to not surprise the thread that made the suspend request. 1867 while (true) { 1868 { 1869 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1870 if (!is_external_suspend()) { 1871 set_terminated(_thread_exiting); 1872 ThreadService::current_thread_exiting(this); 1873 break; 1874 } 1875 // Implied else: 1876 // Things get a little tricky here. We have a pending external 1877 // suspend request, but we are holding the SR_lock so we 1878 // can't just self-suspend. So we temporarily drop the lock 1879 // and then self-suspend. 1880 } 1881 1882 ThreadBlockInVM tbivm(this); 1883 java_suspend_self(); 1884 1885 // We're done with this suspend request, but we have to loop around 1886 // and check again. Eventually we will get SR_lock without a pending 1887 // external suspend request and will be able to mark ourselves as 1888 // exiting. 1889 } 1890 // no more external suspends are allowed at this point 1891 } else { 1892 // before_exit() has already posted JVMTI THREAD_END events 1893 } 1894 1895 if (log_is_enabled(Debug, os, thread, timer)) { 1896 _timer_exit_phase1.stop(); 1897 _timer_exit_phase2.start(); 1898 } 1899 // Notify waiters on thread object. This has to be done after exit() is called 1900 // on the thread (if the thread is the last thread in a daemon ThreadGroup the 1901 // group should have the destroyed bit set before waiters are notified). 1902 ensure_join(this); 1903 assert(!this->has_pending_exception(), "ensure_join should have cleared"); 1904 1905 if (log_is_enabled(Debug, os, thread, timer)) { 1906 _timer_exit_phase2.stop(); 1907 _timer_exit_phase3.start(); 1908 } 1909 // 6282335 JNI DetachCurrentThread spec states that all Java monitors 1910 // held by this thread must be released. The spec does not distinguish 1911 // between JNI-acquired and regular Java monitors. We can only see 1912 // regular Java monitors here if monitor enter-exit matching is broken. 1913 // 1914 // Optionally release any monitors for regular JavaThread exits. This 1915 // is provided as a work around for any bugs in monitor enter-exit 1916 // matching. This can be expensive so it is not enabled by default. 1917 // 1918 // ensure_join() ignores IllegalThreadStateExceptions, and so does 1919 // ObjectSynchronizer::release_monitors_owned_by_thread(). 1920 if (exit_type == jni_detach || ObjectMonitor::Knob_ExitRelease) { 1921 // Sanity check even though JNI DetachCurrentThread() would have 1922 // returned JNI_ERR if there was a Java frame. JavaThread exit 1923 // should be done executing Java code by the time we get here. 1924 assert(!this->has_last_Java_frame(), 1925 "should not have a Java frame when detaching or exiting"); 1926 ObjectSynchronizer::release_monitors_owned_by_thread(this); 1927 assert(!this->has_pending_exception(), "release_monitors should have cleared"); 1928 } 1929 1930 // These things needs to be done while we are still a Java Thread. Make sure that thread 1931 // is in a consistent state, in case GC happens 1932 assert(_privileged_stack_top == NULL, "must be NULL when we get here"); 1933 1934 if (active_handles() != NULL) { 1935 JNIHandleBlock* block = active_handles(); 1936 set_active_handles(NULL); 1937 JNIHandleBlock::release_block(block); 1938 } 1939 1940 if (free_handle_block() != NULL) { 1941 JNIHandleBlock* block = free_handle_block(); 1942 set_free_handle_block(NULL); 1943 JNIHandleBlock::release_block(block); 1944 } 1945 1946 // These have to be removed while this is still a valid thread. 1947 remove_stack_guard_pages(); 1948 1949 if (UseTLAB) { 1950 tlab().make_parsable(true); // retire TLAB 1951 } 1952 1953 if (JvmtiEnv::environments_might_exist()) { 1954 JvmtiExport::cleanup_thread(this); 1955 } 1956 1957 // We must flush any deferred card marks and other various GC barrier 1958 // related buffers (e.g. G1 SATB buffer and G1 dirty card queue buffer) 1959 // before removing a thread from the list of active threads. 1960 BarrierSet::barrier_set()->on_thread_detach(this); 1961 1962 log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").", 1963 exit_type == JavaThread::normal_exit ? "exiting" : "detaching", 1964 os::current_thread_id()); 1965 1966 if (log_is_enabled(Debug, os, thread, timer)) { 1967 _timer_exit_phase3.stop(); 1968 _timer_exit_phase4.start(); 1969 } 1970 // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread 1971 Threads::remove(this); 1972 1973 if (log_is_enabled(Debug, os, thread, timer)) { 1974 _timer_exit_phase4.stop(); 1975 ResourceMark rm(this); 1976 log_debug(os, thread, timer)("name='%s'" 1977 ", exit-phase1=" JLONG_FORMAT 1978 ", exit-phase2=" JLONG_FORMAT 1979 ", exit-phase3=" JLONG_FORMAT 1980 ", exit-phase4=" JLONG_FORMAT, 1981 get_thread_name(), 1982 _timer_exit_phase1.milliseconds(), 1983 _timer_exit_phase2.milliseconds(), 1984 _timer_exit_phase3.milliseconds(), 1985 _timer_exit_phase4.milliseconds()); 1986 } 1987 } 1988 1989 void JavaThread::cleanup_failed_attach_current_thread() { 1990 if (active_handles() != NULL) { 1991 JNIHandleBlock* block = active_handles(); 1992 set_active_handles(NULL); 1993 JNIHandleBlock::release_block(block); 1994 } 1995 1996 if (free_handle_block() != NULL) { 1997 JNIHandleBlock* block = free_handle_block(); 1998 set_free_handle_block(NULL); 1999 JNIHandleBlock::release_block(block); 2000 } 2001 2002 // These have to be removed while this is still a valid thread. 2003 remove_stack_guard_pages(); 2004 2005 if (UseTLAB) { 2006 tlab().make_parsable(true); // retire TLAB, if any 2007 } 2008 2009 BarrierSet::barrier_set()->on_thread_detach(this); 2010 2011 Threads::remove(this); 2012 this->smr_delete(); 2013 } 2014 2015 JavaThread* JavaThread::active() { 2016 Thread* thread = Thread::current(); 2017 if (thread->is_Java_thread()) { 2018 return (JavaThread*) thread; 2019 } else { 2020 assert(thread->is_VM_thread(), "this must be a vm thread"); 2021 VM_Operation* op = ((VMThread*) thread)->vm_operation(); 2022 JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread(); 2023 assert(ret->is_Java_thread(), "must be a Java thread"); 2024 return ret; 2025 } 2026 } 2027 2028 bool JavaThread::is_lock_owned(address adr) const { 2029 if (Thread::is_lock_owned(adr)) return true; 2030 2031 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { 2032 if (chunk->contains(adr)) return true; 2033 } 2034 2035 return false; 2036 } 2037 2038 2039 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) { 2040 chunk->set_next(monitor_chunks()); 2041 set_monitor_chunks(chunk); 2042 } 2043 2044 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) { 2045 guarantee(monitor_chunks() != NULL, "must be non empty"); 2046 if (monitor_chunks() == chunk) { 2047 set_monitor_chunks(chunk->next()); 2048 } else { 2049 MonitorChunk* prev = monitor_chunks(); 2050 while (prev->next() != chunk) prev = prev->next(); 2051 prev->set_next(chunk->next()); 2052 } 2053 } 2054 2055 // JVM support. 2056 2057 // Note: this function shouldn't block if it's called in 2058 // _thread_in_native_trans state (such as from 2059 // check_special_condition_for_native_trans()). 2060 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) { 2061 2062 if (has_last_Java_frame() && has_async_condition()) { 2063 // If we are at a polling page safepoint (not a poll return) 2064 // then we must defer async exception because live registers 2065 // will be clobbered by the exception path. Poll return is 2066 // ok because the call we a returning from already collides 2067 // with exception handling registers and so there is no issue. 2068 // (The exception handling path kills call result registers but 2069 // this is ok since the exception kills the result anyway). 2070 2071 if (is_at_poll_safepoint()) { 2072 // if the code we are returning to has deoptimized we must defer 2073 // the exception otherwise live registers get clobbered on the 2074 // exception path before deoptimization is able to retrieve them. 2075 // 2076 RegisterMap map(this, false); 2077 frame caller_fr = last_frame().sender(&map); 2078 assert(caller_fr.is_compiled_frame(), "what?"); 2079 if (caller_fr.is_deoptimized_frame()) { 2080 log_info(exceptions)("deferred async exception at compiled safepoint"); 2081 return; 2082 } 2083 } 2084 } 2085 2086 JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition(); 2087 if (condition == _no_async_condition) { 2088 // Conditions have changed since has_special_runtime_exit_condition() 2089 // was called: 2090 // - if we were here only because of an external suspend request, 2091 // then that was taken care of above (or cancelled) so we are done 2092 // - if we were here because of another async request, then it has 2093 // been cleared between the has_special_runtime_exit_condition() 2094 // and now so again we are done 2095 return; 2096 } 2097 2098 // Check for pending async. exception 2099 if (_pending_async_exception != NULL) { 2100 // Only overwrite an already pending exception, if it is not a threadDeath. 2101 if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) { 2102 2103 // We cannot call Exceptions::_throw(...) here because we cannot block 2104 set_pending_exception(_pending_async_exception, __FILE__, __LINE__); 2105 2106 LogTarget(Info, exceptions) lt; 2107 if (lt.is_enabled()) { 2108 ResourceMark rm; 2109 LogStream ls(lt); 2110 ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this)); 2111 if (has_last_Java_frame()) { 2112 frame f = last_frame(); 2113 ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp())); 2114 } 2115 ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name()); 2116 } 2117 _pending_async_exception = NULL; 2118 clear_has_async_exception(); 2119 } 2120 } 2121 2122 if (check_unsafe_error && 2123 condition == _async_unsafe_access_error && !has_pending_exception()) { 2124 condition = _no_async_condition; // done 2125 switch (thread_state()) { 2126 case _thread_in_vm: { 2127 JavaThread* THREAD = this; 2128 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation"); 2129 } 2130 case _thread_in_native: { 2131 ThreadInVMfromNative tiv(this); 2132 JavaThread* THREAD = this; 2133 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation"); 2134 } 2135 case _thread_in_Java: { 2136 ThreadInVMfromJava tiv(this); 2137 JavaThread* THREAD = this; 2138 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code"); 2139 } 2140 default: 2141 ShouldNotReachHere(); 2142 } 2143 } 2144 2145 assert(condition == _no_async_condition || has_pending_exception() || 2146 (!check_unsafe_error && condition == _async_unsafe_access_error), 2147 "must have handled the async condition, if no exception"); 2148 } 2149 2150 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) { 2151 // 2152 // Check for pending external suspend. Internal suspend requests do 2153 // not use handle_special_runtime_exit_condition(). 2154 // If JNIEnv proxies are allowed, don't self-suspend if the target 2155 // thread is not the current thread. In older versions of jdbx, jdbx 2156 // threads could call into the VM with another thread's JNIEnv so we 2157 // can be here operating on behalf of a suspended thread (4432884). 2158 bool do_self_suspend = is_external_suspend_with_lock(); 2159 if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) { 2160 // 2161 // Because thread is external suspended the safepoint code will count 2162 // thread as at a safepoint. This can be odd because we can be here 2163 // as _thread_in_Java which would normally transition to _thread_blocked 2164 // at a safepoint. We would like to mark the thread as _thread_blocked 2165 // before calling java_suspend_self like all other callers of it but 2166 // we must then observe proper safepoint protocol. (We can't leave 2167 // _thread_blocked with a safepoint in progress). However we can be 2168 // here as _thread_in_native_trans so we can't use a normal transition 2169 // constructor/destructor pair because they assert on that type of 2170 // transition. We could do something like: 2171 // 2172 // JavaThreadState state = thread_state(); 2173 // set_thread_state(_thread_in_vm); 2174 // { 2175 // ThreadBlockInVM tbivm(this); 2176 // java_suspend_self() 2177 // } 2178 // set_thread_state(_thread_in_vm_trans); 2179 // if (safepoint) block; 2180 // set_thread_state(state); 2181 // 2182 // but that is pretty messy. Instead we just go with the way the 2183 // code has worked before and note that this is the only path to 2184 // java_suspend_self that doesn't put the thread in _thread_blocked 2185 // mode. 2186 2187 frame_anchor()->make_walkable(this); 2188 java_suspend_self(); 2189 2190 // We might be here for reasons in addition to the self-suspend request 2191 // so check for other async requests. 2192 } 2193 2194 if (check_asyncs) { 2195 check_and_handle_async_exceptions(); 2196 } 2197 2198 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);) 2199 } 2200 2201 void JavaThread::send_thread_stop(oop java_throwable) { 2202 assert(Thread::current()->is_VM_thread(), "should be in the vm thread"); 2203 assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code"); 2204 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); 2205 2206 // Do not throw asynchronous exceptions against the compiler thread 2207 // (the compiler thread should not be a Java thread -- fix in 1.4.2) 2208 if (!can_call_java()) return; 2209 2210 { 2211 // Actually throw the Throwable against the target Thread - however 2212 // only if there is no thread death exception installed already. 2213 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) { 2214 // If the topmost frame is a runtime stub, then we are calling into 2215 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..) 2216 // must deoptimize the caller before continuing, as the compiled exception handler table 2217 // may not be valid 2218 if (has_last_Java_frame()) { 2219 frame f = last_frame(); 2220 if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) { 2221 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 2222 RegisterMap reg_map(this, UseBiasedLocking); 2223 frame compiled_frame = f.sender(®_map); 2224 if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) { 2225 Deoptimization::deoptimize(this, compiled_frame, ®_map); 2226 } 2227 } 2228 } 2229 2230 // Set async. pending exception in thread. 2231 set_pending_async_exception(java_throwable); 2232 2233 if (log_is_enabled(Info, exceptions)) { 2234 ResourceMark rm; 2235 log_info(exceptions)("Pending Async. exception installed of type: %s", 2236 InstanceKlass::cast(_pending_async_exception->klass())->external_name()); 2237 } 2238 // for AbortVMOnException flag 2239 Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name()); 2240 } 2241 } 2242 2243 2244 // Interrupt thread so it will wake up from a potential wait() 2245 Thread::interrupt(this); 2246 } 2247 2248 // External suspension mechanism. 2249 // 2250 // Tell the VM to suspend a thread when ever it knows that it does not hold on 2251 // to any VM_locks and it is at a transition 2252 // Self-suspension will happen on the transition out of the vm. 2253 // Catch "this" coming in from JNIEnv pointers when the thread has been freed 2254 // 2255 // Guarantees on return: 2256 // + Target thread will not execute any new bytecode (that's why we need to 2257 // force a safepoint) 2258 // + Target thread will not enter any new monitors 2259 // 2260 void JavaThread::java_suspend() { 2261 ThreadsListHandle tlh; 2262 if (!tlh.includes(this) || threadObj() == NULL || is_exiting()) { 2263 return; 2264 } 2265 2266 { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 2267 if (!is_external_suspend()) { 2268 // a racing resume has cancelled us; bail out now 2269 return; 2270 } 2271 2272 // suspend is done 2273 uint32_t debug_bits = 0; 2274 // Warning: is_ext_suspend_completed() may temporarily drop the 2275 // SR_lock to allow the thread to reach a stable thread state if 2276 // it is currently in a transient thread state. 2277 if (is_ext_suspend_completed(false /* !called_by_wait */, 2278 SuspendRetryDelay, &debug_bits)) { 2279 return; 2280 } 2281 } 2282 2283 VM_ThreadSuspend vm_suspend; 2284 VMThread::execute(&vm_suspend); 2285 } 2286 2287 // Part II of external suspension. 2288 // A JavaThread self suspends when it detects a pending external suspend 2289 // request. This is usually on transitions. It is also done in places 2290 // where continuing to the next transition would surprise the caller, 2291 // e.g., monitor entry. 2292 // 2293 // Returns the number of times that the thread self-suspended. 2294 // 2295 // Note: DO NOT call java_suspend_self() when you just want to block current 2296 // thread. java_suspend_self() is the second stage of cooperative 2297 // suspension for external suspend requests and should only be used 2298 // to complete an external suspend request. 2299 // 2300 int JavaThread::java_suspend_self() { 2301 int ret = 0; 2302 2303 // we are in the process of exiting so don't suspend 2304 if (is_exiting()) { 2305 clear_external_suspend(); 2306 return ret; 2307 } 2308 2309 assert(_anchor.walkable() || 2310 (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()), 2311 "must have walkable stack"); 2312 2313 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 2314 2315 assert(!this->is_ext_suspended(), 2316 "a thread trying to self-suspend should not already be suspended"); 2317 2318 if (this->is_suspend_equivalent()) { 2319 // If we are self-suspending as a result of the lifting of a 2320 // suspend equivalent condition, then the suspend_equivalent 2321 // flag is not cleared until we set the ext_suspended flag so 2322 // that wait_for_ext_suspend_completion() returns consistent 2323 // results. 2324 this->clear_suspend_equivalent(); 2325 } 2326 2327 // A racing resume may have cancelled us before we grabbed SR_lock 2328 // above. Or another external suspend request could be waiting for us 2329 // by the time we return from SR_lock()->wait(). The thread 2330 // that requested the suspension may already be trying to walk our 2331 // stack and if we return now, we can change the stack out from under 2332 // it. This would be a "bad thing (TM)" and cause the stack walker 2333 // to crash. We stay self-suspended until there are no more pending 2334 // external suspend requests. 2335 while (is_external_suspend()) { 2336 ret++; 2337 this->set_ext_suspended(); 2338 2339 // _ext_suspended flag is cleared by java_resume() 2340 while (is_ext_suspended()) { 2341 this->SR_lock()->wait(Mutex::_no_safepoint_check_flag); 2342 } 2343 } 2344 2345 return ret; 2346 } 2347 2348 #ifdef ASSERT 2349 // Verify the JavaThread has not yet been published in the Threads::list, and 2350 // hence doesn't need protection from concurrent access at this stage. 2351 void JavaThread::verify_not_published() { 2352 // Cannot create a ThreadsListHandle here and check !tlh.includes(this) 2353 // since an unpublished JavaThread doesn't participate in the 2354 // Thread-SMR protocol for keeping a ThreadsList alive. 2355 assert(!on_thread_list(), "JavaThread shouldn't have been published yet!"); 2356 } 2357 #endif 2358 2359 // Slow path when the native==>VM/Java barriers detect a safepoint is in 2360 // progress or when _suspend_flags is non-zero. 2361 // Current thread needs to self-suspend if there is a suspend request and/or 2362 // block if a safepoint is in progress. 2363 // Async exception ISN'T checked. 2364 // Note only the ThreadInVMfromNative transition can call this function 2365 // directly and when thread state is _thread_in_native_trans 2366 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) { 2367 assert(thread->thread_state() == _thread_in_native_trans, "wrong state"); 2368 2369 JavaThread *curJT = JavaThread::current(); 2370 bool do_self_suspend = thread->is_external_suspend(); 2371 2372 assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition"); 2373 2374 // If JNIEnv proxies are allowed, don't self-suspend if the target 2375 // thread is not the current thread. In older versions of jdbx, jdbx 2376 // threads could call into the VM with another thread's JNIEnv so we 2377 // can be here operating on behalf of a suspended thread (4432884). 2378 if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) { 2379 JavaThreadState state = thread->thread_state(); 2380 2381 // We mark this thread_blocked state as a suspend-equivalent so 2382 // that a caller to is_ext_suspend_completed() won't be confused. 2383 // The suspend-equivalent state is cleared by java_suspend_self(). 2384 thread->set_suspend_equivalent(); 2385 2386 // If the safepoint code sees the _thread_in_native_trans state, it will 2387 // wait until the thread changes to other thread state. There is no 2388 // guarantee on how soon we can obtain the SR_lock and complete the 2389 // self-suspend request. It would be a bad idea to let safepoint wait for 2390 // too long. Temporarily change the state to _thread_blocked to 2391 // let the VM thread know that this thread is ready for GC. The problem 2392 // of changing thread state is that safepoint could happen just after 2393 // java_suspend_self() returns after being resumed, and VM thread will 2394 // see the _thread_blocked state. We must check for safepoint 2395 // after restoring the state and make sure we won't leave while a safepoint 2396 // is in progress. 2397 thread->set_thread_state(_thread_blocked); 2398 thread->java_suspend_self(); 2399 thread->set_thread_state(state); 2400 2401 InterfaceSupport::serialize_thread_state_with_handler(thread); 2402 } 2403 2404 SafepointMechanism::block_if_requested(curJT); 2405 2406 if (thread->is_deopt_suspend()) { 2407 thread->clear_deopt_suspend(); 2408 RegisterMap map(thread, false); 2409 frame f = thread->last_frame(); 2410 while (f.id() != thread->must_deopt_id() && ! f.is_first_frame()) { 2411 f = f.sender(&map); 2412 } 2413 if (f.id() == thread->must_deopt_id()) { 2414 thread->clear_must_deopt_id(); 2415 f.deoptimize(thread); 2416 } else { 2417 fatal("missed deoptimization!"); 2418 } 2419 } 2420 2421 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(thread);) 2422 } 2423 2424 // Slow path when the native==>VM/Java barriers detect a safepoint is in 2425 // progress or when _suspend_flags is non-zero. 2426 // Current thread needs to self-suspend if there is a suspend request and/or 2427 // block if a safepoint is in progress. 2428 // Also check for pending async exception (not including unsafe access error). 2429 // Note only the native==>VM/Java barriers can call this function and when 2430 // thread state is _thread_in_native_trans. 2431 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) { 2432 check_safepoint_and_suspend_for_native_trans(thread); 2433 2434 if (thread->has_async_exception()) { 2435 // We are in _thread_in_native_trans state, don't handle unsafe 2436 // access error since that may block. 2437 thread->check_and_handle_async_exceptions(false); 2438 } 2439 } 2440 2441 // This is a variant of the normal 2442 // check_special_condition_for_native_trans with slightly different 2443 // semantics for use by critical native wrappers. It does all the 2444 // normal checks but also performs the transition back into 2445 // thread_in_Java state. This is required so that critical natives 2446 // can potentially block and perform a GC if they are the last thread 2447 // exiting the GCLocker. 2448 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) { 2449 check_special_condition_for_native_trans(thread); 2450 2451 // Finish the transition 2452 thread->set_thread_state(_thread_in_Java); 2453 2454 if (thread->do_critical_native_unlock()) { 2455 ThreadInVMfromJavaNoAsyncException tiv(thread); 2456 GCLocker::unlock_critical(thread); 2457 thread->clear_critical_native_unlock(); 2458 } 2459 } 2460 2461 // We need to guarantee the Threads_lock here, since resumes are not 2462 // allowed during safepoint synchronization 2463 // Can only resume from an external suspension 2464 void JavaThread::java_resume() { 2465 assert_locked_or_safepoint(Threads_lock); 2466 2467 // Sanity check: thread is gone, has started exiting or the thread 2468 // was not externally suspended. 2469 ThreadsListHandle tlh; 2470 if (!tlh.includes(this) || is_exiting() || !is_external_suspend()) { 2471 return; 2472 } 2473 2474 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 2475 2476 clear_external_suspend(); 2477 2478 if (is_ext_suspended()) { 2479 clear_ext_suspended(); 2480 SR_lock()->notify_all(); 2481 } 2482 } 2483 2484 size_t JavaThread::_stack_red_zone_size = 0; 2485 size_t JavaThread::_stack_yellow_zone_size = 0; 2486 size_t JavaThread::_stack_reserved_zone_size = 0; 2487 size_t JavaThread::_stack_shadow_zone_size = 0; 2488 2489 void JavaThread::create_stack_guard_pages() { 2490 if (!os::uses_stack_guard_pages() || 2491 _stack_guard_state != stack_guard_unused || 2492 (DisablePrimordialThreadGuardPages && os::is_primordial_thread())) { 2493 log_info(os, thread)("Stack guard page creation for thread " 2494 UINTX_FORMAT " disabled", os::current_thread_id()); 2495 return; 2496 } 2497 address low_addr = stack_end(); 2498 size_t len = stack_guard_zone_size(); 2499 2500 assert(is_aligned(low_addr, os::vm_page_size()), "Stack base should be the start of a page"); 2501 assert(is_aligned(len, os::vm_page_size()), "Stack size should be a multiple of page size"); 2502 2503 int must_commit = os::must_commit_stack_guard_pages(); 2504 // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len); 2505 2506 if (must_commit && !os::create_stack_guard_pages((char *) low_addr, len)) { 2507 log_warning(os, thread)("Attempt to allocate stack guard pages failed."); 2508 return; 2509 } 2510 2511 if (os::guard_memory((char *) low_addr, len)) { 2512 _stack_guard_state = stack_guard_enabled; 2513 } else { 2514 log_warning(os, thread)("Attempt to protect stack guard pages failed (" 2515 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len)); 2516 if (os::uncommit_memory((char *) low_addr, len)) { 2517 log_warning(os, thread)("Attempt to deallocate stack guard pages failed."); 2518 } 2519 return; 2520 } 2521 2522 log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages activated: " 2523 PTR_FORMAT "-" PTR_FORMAT ".", 2524 os::current_thread_id(), p2i(low_addr), p2i(low_addr + len)); 2525 } 2526 2527 void JavaThread::remove_stack_guard_pages() { 2528 assert(Thread::current() == this, "from different thread"); 2529 if (_stack_guard_state == stack_guard_unused) return; 2530 address low_addr = stack_end(); 2531 size_t len = stack_guard_zone_size(); 2532 2533 if (os::must_commit_stack_guard_pages()) { 2534 if (os::remove_stack_guard_pages((char *) low_addr, len)) { 2535 _stack_guard_state = stack_guard_unused; 2536 } else { 2537 log_warning(os, thread)("Attempt to deallocate stack guard pages failed (" 2538 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len)); 2539 return; 2540 } 2541 } else { 2542 if (_stack_guard_state == stack_guard_unused) return; 2543 if (os::unguard_memory((char *) low_addr, len)) { 2544 _stack_guard_state = stack_guard_unused; 2545 } else { 2546 log_warning(os, thread)("Attempt to unprotect stack guard pages failed (" 2547 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len)); 2548 return; 2549 } 2550 } 2551 2552 log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages removed: " 2553 PTR_FORMAT "-" PTR_FORMAT ".", 2554 os::current_thread_id(), p2i(low_addr), p2i(low_addr + len)); 2555 } 2556 2557 void JavaThread::enable_stack_reserved_zone() { 2558 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2559 assert(_stack_guard_state != stack_guard_enabled, "already enabled"); 2560 2561 // The base notation is from the stack's point of view, growing downward. 2562 // We need to adjust it to work correctly with guard_memory() 2563 address base = stack_reserved_zone_base() - stack_reserved_zone_size(); 2564 2565 guarantee(base < stack_base(),"Error calculating stack reserved zone"); 2566 guarantee(base < os::current_stack_pointer(),"Error calculating stack reserved zone"); 2567 2568 if (os::guard_memory((char *) base, stack_reserved_zone_size())) { 2569 _stack_guard_state = stack_guard_enabled; 2570 } else { 2571 warning("Attempt to guard stack reserved zone failed."); 2572 } 2573 enable_register_stack_guard(); 2574 } 2575 2576 void JavaThread::disable_stack_reserved_zone() { 2577 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2578 assert(_stack_guard_state != stack_guard_reserved_disabled, "already disabled"); 2579 2580 // Simply return if called for a thread that does not use guard pages. 2581 if (_stack_guard_state == stack_guard_unused) return; 2582 2583 // The base notation is from the stack's point of view, growing downward. 2584 // We need to adjust it to work correctly with guard_memory() 2585 address base = stack_reserved_zone_base() - stack_reserved_zone_size(); 2586 2587 if (os::unguard_memory((char *)base, stack_reserved_zone_size())) { 2588 _stack_guard_state = stack_guard_reserved_disabled; 2589 } else { 2590 warning("Attempt to unguard stack reserved zone failed."); 2591 } 2592 disable_register_stack_guard(); 2593 } 2594 2595 void JavaThread::enable_stack_yellow_reserved_zone() { 2596 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2597 assert(_stack_guard_state != stack_guard_enabled, "already enabled"); 2598 2599 // The base notation is from the stacks point of view, growing downward. 2600 // We need to adjust it to work correctly with guard_memory() 2601 address base = stack_red_zone_base(); 2602 2603 guarantee(base < stack_base(), "Error calculating stack yellow zone"); 2604 guarantee(base < os::current_stack_pointer(), "Error calculating stack yellow zone"); 2605 2606 if (os::guard_memory((char *) base, stack_yellow_reserved_zone_size())) { 2607 _stack_guard_state = stack_guard_enabled; 2608 } else { 2609 warning("Attempt to guard stack yellow zone failed."); 2610 } 2611 enable_register_stack_guard(); 2612 } 2613 2614 void JavaThread::disable_stack_yellow_reserved_zone() { 2615 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2616 assert(_stack_guard_state != stack_guard_yellow_reserved_disabled, "already disabled"); 2617 2618 // Simply return if called for a thread that does not use guard pages. 2619 if (_stack_guard_state == stack_guard_unused) return; 2620 2621 // The base notation is from the stacks point of view, growing downward. 2622 // We need to adjust it to work correctly with guard_memory() 2623 address base = stack_red_zone_base(); 2624 2625 if (os::unguard_memory((char *)base, stack_yellow_reserved_zone_size())) { 2626 _stack_guard_state = stack_guard_yellow_reserved_disabled; 2627 } else { 2628 warning("Attempt to unguard stack yellow zone failed."); 2629 } 2630 disable_register_stack_guard(); 2631 } 2632 2633 void JavaThread::enable_stack_red_zone() { 2634 // The base notation is from the stacks point of view, growing downward. 2635 // We need to adjust it to work correctly with guard_memory() 2636 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2637 address base = stack_red_zone_base() - stack_red_zone_size(); 2638 2639 guarantee(base < stack_base(), "Error calculating stack red zone"); 2640 guarantee(base < os::current_stack_pointer(), "Error calculating stack red zone"); 2641 2642 if (!os::guard_memory((char *) base, stack_red_zone_size())) { 2643 warning("Attempt to guard stack red zone failed."); 2644 } 2645 } 2646 2647 void JavaThread::disable_stack_red_zone() { 2648 // The base notation is from the stacks point of view, growing downward. 2649 // We need to adjust it to work correctly with guard_memory() 2650 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2651 address base = stack_red_zone_base() - stack_red_zone_size(); 2652 if (!os::unguard_memory((char *)base, stack_red_zone_size())) { 2653 warning("Attempt to unguard stack red zone failed."); 2654 } 2655 } 2656 2657 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) { 2658 // ignore is there is no stack 2659 if (!has_last_Java_frame()) return; 2660 // traverse the stack frames. Starts from top frame. 2661 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2662 frame* fr = fst.current(); 2663 f(fr, fst.register_map()); 2664 } 2665 } 2666 2667 2668 #ifndef PRODUCT 2669 // Deoptimization 2670 // Function for testing deoptimization 2671 void JavaThread::deoptimize() { 2672 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 2673 StackFrameStream fst(this, UseBiasedLocking); 2674 bool deopt = false; // Dump stack only if a deopt actually happens. 2675 bool only_at = strlen(DeoptimizeOnlyAt) > 0; 2676 // Iterate over all frames in the thread and deoptimize 2677 for (; !fst.is_done(); fst.next()) { 2678 if (fst.current()->can_be_deoptimized()) { 2679 2680 if (only_at) { 2681 // Deoptimize only at particular bcis. DeoptimizeOnlyAt 2682 // consists of comma or carriage return separated numbers so 2683 // search for the current bci in that string. 2684 address pc = fst.current()->pc(); 2685 nmethod* nm = (nmethod*) fst.current()->cb(); 2686 ScopeDesc* sd = nm->scope_desc_at(pc); 2687 char buffer[8]; 2688 jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci()); 2689 size_t len = strlen(buffer); 2690 const char * found = strstr(DeoptimizeOnlyAt, buffer); 2691 while (found != NULL) { 2692 if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') && 2693 (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) { 2694 // Check that the bci found is bracketed by terminators. 2695 break; 2696 } 2697 found = strstr(found + 1, buffer); 2698 } 2699 if (!found) { 2700 continue; 2701 } 2702 } 2703 2704 if (DebugDeoptimization && !deopt) { 2705 deopt = true; // One-time only print before deopt 2706 tty->print_cr("[BEFORE Deoptimization]"); 2707 trace_frames(); 2708 trace_stack(); 2709 } 2710 Deoptimization::deoptimize(this, *fst.current(), fst.register_map()); 2711 } 2712 } 2713 2714 if (DebugDeoptimization && deopt) { 2715 tty->print_cr("[AFTER Deoptimization]"); 2716 trace_frames(); 2717 } 2718 } 2719 2720 2721 // Make zombies 2722 void JavaThread::make_zombies() { 2723 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2724 if (fst.current()->can_be_deoptimized()) { 2725 // it is a Java nmethod 2726 nmethod* nm = CodeCache::find_nmethod(fst.current()->pc()); 2727 nm->make_not_entrant(); 2728 } 2729 } 2730 } 2731 #endif // PRODUCT 2732 2733 2734 void JavaThread::deoptimized_wrt_marked_nmethods() { 2735 if (!has_last_Java_frame()) return; 2736 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 2737 StackFrameStream fst(this, UseBiasedLocking); 2738 for (; !fst.is_done(); fst.next()) { 2739 if (fst.current()->should_be_deoptimized()) { 2740 Deoptimization::deoptimize(this, *fst.current(), fst.register_map()); 2741 } 2742 } 2743 } 2744 2745 2746 // If the caller is a NamedThread, then remember, in the current scope, 2747 // the given JavaThread in its _processed_thread field. 2748 class RememberProcessedThread: public StackObj { 2749 NamedThread* _cur_thr; 2750 public: 2751 RememberProcessedThread(JavaThread* jthr) { 2752 Thread* thread = Thread::current(); 2753 if (thread->is_Named_thread()) { 2754 _cur_thr = (NamedThread *)thread; 2755 _cur_thr->set_processed_thread(jthr); 2756 } else { 2757 _cur_thr = NULL; 2758 } 2759 } 2760 2761 ~RememberProcessedThread() { 2762 if (_cur_thr) { 2763 _cur_thr->set_processed_thread(NULL); 2764 } 2765 } 2766 }; 2767 2768 void JavaThread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 2769 // Verify that the deferred card marks have been flushed. 2770 assert(deferred_card_mark().is_empty(), "Should be empty during GC"); 2771 2772 // Traverse the GCHandles 2773 Thread::oops_do(f, cf); 2774 2775 assert((!has_last_Java_frame() && java_call_counter() == 0) || 2776 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); 2777 2778 if (has_last_Java_frame()) { 2779 // Record JavaThread to GC thread 2780 RememberProcessedThread rpt(this); 2781 2782 // Traverse the privileged stack 2783 if (_privileged_stack_top != NULL) { 2784 _privileged_stack_top->oops_do(f); 2785 } 2786 2787 // traverse the registered growable array 2788 if (_array_for_gc != NULL) { 2789 for (int index = 0; index < _array_for_gc->length(); index++) { 2790 f->do_oop(_array_for_gc->adr_at(index)); 2791 } 2792 } 2793 2794 // Traverse the monitor chunks 2795 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { 2796 chunk->oops_do(f); 2797 } 2798 2799 // Traverse the execution stack 2800 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2801 fst.current()->oops_do(f, cf, fst.register_map()); 2802 } 2803 } 2804 2805 // callee_target is never live across a gc point so NULL it here should 2806 // it still contain a methdOop. 2807 2808 set_callee_target(NULL); 2809 2810 assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!"); 2811 // If we have deferred set_locals there might be oops waiting to be 2812 // written 2813 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals(); 2814 if (list != NULL) { 2815 for (int i = 0; i < list->length(); i++) { 2816 list->at(i)->oops_do(f); 2817 } 2818 } 2819 2820 // Traverse instance variables at the end since the GC may be moving things 2821 // around using this function 2822 f->do_oop((oop*) &_threadObj); 2823 f->do_oop((oop*) &_vm_result); 2824 f->do_oop((oop*) &_exception_oop); 2825 f->do_oop((oop*) &_pending_async_exception); 2826 2827 if (jvmti_thread_state() != NULL) { 2828 jvmti_thread_state()->oops_do(f); 2829 } 2830 } 2831 2832 void JavaThread::nmethods_do(CodeBlobClosure* cf) { 2833 assert((!has_last_Java_frame() && java_call_counter() == 0) || 2834 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); 2835 2836 if (has_last_Java_frame()) { 2837 // Traverse the execution stack 2838 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2839 fst.current()->nmethods_do(cf); 2840 } 2841 } 2842 } 2843 2844 void JavaThread::metadata_do(void f(Metadata*)) { 2845 if (has_last_Java_frame()) { 2846 // Traverse the execution stack to call f() on the methods in the stack 2847 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2848 fst.current()->metadata_do(f); 2849 } 2850 } else if (is_Compiler_thread()) { 2851 // need to walk ciMetadata in current compile tasks to keep alive. 2852 CompilerThread* ct = (CompilerThread*)this; 2853 if (ct->env() != NULL) { 2854 ct->env()->metadata_do(f); 2855 } 2856 CompileTask* task = ct->task(); 2857 if (task != NULL) { 2858 task->metadata_do(f); 2859 } 2860 } 2861 } 2862 2863 // Printing 2864 const char* _get_thread_state_name(JavaThreadState _thread_state) { 2865 switch (_thread_state) { 2866 case _thread_uninitialized: return "_thread_uninitialized"; 2867 case _thread_new: return "_thread_new"; 2868 case _thread_new_trans: return "_thread_new_trans"; 2869 case _thread_in_native: return "_thread_in_native"; 2870 case _thread_in_native_trans: return "_thread_in_native_trans"; 2871 case _thread_in_vm: return "_thread_in_vm"; 2872 case _thread_in_vm_trans: return "_thread_in_vm_trans"; 2873 case _thread_in_Java: return "_thread_in_Java"; 2874 case _thread_in_Java_trans: return "_thread_in_Java_trans"; 2875 case _thread_blocked: return "_thread_blocked"; 2876 case _thread_blocked_trans: return "_thread_blocked_trans"; 2877 default: return "unknown thread state"; 2878 } 2879 } 2880 2881 #ifndef PRODUCT 2882 void JavaThread::print_thread_state_on(outputStream *st) const { 2883 st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state)); 2884 }; 2885 void JavaThread::print_thread_state() const { 2886 print_thread_state_on(tty); 2887 } 2888 #endif // PRODUCT 2889 2890 // Called by Threads::print() for VM_PrintThreads operation 2891 void JavaThread::print_on(outputStream *st, bool print_extended_info) const { 2892 st->print_raw("\""); 2893 st->print_raw(get_thread_name()); 2894 st->print_raw("\" "); 2895 oop thread_oop = threadObj(); 2896 if (thread_oop != NULL) { 2897 st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop)); 2898 if (java_lang_Thread::is_daemon(thread_oop)) st->print("daemon "); 2899 st->print("prio=%d ", java_lang_Thread::priority(thread_oop)); 2900 } 2901 Thread::print_on(st, print_extended_info); 2902 // print guess for valid stack memory region (assume 4K pages); helps lock debugging 2903 st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12)); 2904 if (thread_oop != NULL) { 2905 st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop)); 2906 } 2907 #ifndef PRODUCT 2908 print_thread_state_on(st); 2909 _safepoint_state->print_on(st); 2910 #endif // PRODUCT 2911 if (is_Compiler_thread()) { 2912 CompileTask *task = ((CompilerThread*)this)->task(); 2913 if (task != NULL) { 2914 st->print(" Compiling: "); 2915 task->print(st, NULL, true, false); 2916 } else { 2917 st->print(" No compile task"); 2918 } 2919 st->cr(); 2920 } 2921 } 2922 2923 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const { 2924 st->print("%s", get_thread_name_string(buf, buflen)); 2925 } 2926 2927 // Called by fatal error handler. The difference between this and 2928 // JavaThread::print() is that we can't grab lock or allocate memory. 2929 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const { 2930 st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen)); 2931 oop thread_obj = threadObj(); 2932 if (thread_obj != NULL) { 2933 if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon"); 2934 } 2935 st->print(" ["); 2936 st->print("%s", _get_thread_state_name(_thread_state)); 2937 if (osthread()) { 2938 st->print(", id=%d", osthread()->thread_id()); 2939 } 2940 st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")", 2941 p2i(stack_end()), p2i(stack_base())); 2942 st->print("]"); 2943 2944 ThreadsSMRSupport::print_info_on(this, st); 2945 return; 2946 } 2947 2948 // Verification 2949 2950 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); } 2951 2952 void JavaThread::verify() { 2953 // Verify oops in the thread. 2954 oops_do(&VerifyOopClosure::verify_oop, NULL); 2955 2956 // Verify the stack frames. 2957 frames_do(frame_verify); 2958 } 2959 2960 // CR 6300358 (sub-CR 2137150) 2961 // Most callers of this method assume that it can't return NULL but a 2962 // thread may not have a name whilst it is in the process of attaching to 2963 // the VM - see CR 6412693, and there are places where a JavaThread can be 2964 // seen prior to having it's threadObj set (eg JNI attaching threads and 2965 // if vm exit occurs during initialization). These cases can all be accounted 2966 // for such that this method never returns NULL. 2967 const char* JavaThread::get_thread_name() const { 2968 #ifdef ASSERT 2969 // early safepoints can hit while current thread does not yet have TLS 2970 if (!SafepointSynchronize::is_at_safepoint()) { 2971 Thread *cur = Thread::current(); 2972 if (!(cur->is_Java_thread() && cur == this)) { 2973 // Current JavaThreads are allowed to get their own name without 2974 // the Threads_lock. 2975 assert_locked_or_safepoint(Threads_lock); 2976 } 2977 } 2978 #endif // ASSERT 2979 return get_thread_name_string(); 2980 } 2981 2982 // Returns a non-NULL representation of this thread's name, or a suitable 2983 // descriptive string if there is no set name 2984 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const { 2985 const char* name_str; 2986 oop thread_obj = threadObj(); 2987 if (thread_obj != NULL) { 2988 oop name = java_lang_Thread::name(thread_obj); 2989 if (name != NULL) { 2990 if (buf == NULL) { 2991 name_str = java_lang_String::as_utf8_string(name); 2992 } else { 2993 name_str = java_lang_String::as_utf8_string(name, buf, buflen); 2994 } 2995 } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306 2996 name_str = "<no-name - thread is attaching>"; 2997 } else { 2998 name_str = Thread::name(); 2999 } 3000 } else { 3001 name_str = Thread::name(); 3002 } 3003 assert(name_str != NULL, "unexpected NULL thread name"); 3004 return name_str; 3005 } 3006 3007 3008 const char* JavaThread::get_threadgroup_name() const { 3009 debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);) 3010 oop thread_obj = threadObj(); 3011 if (thread_obj != NULL) { 3012 oop thread_group = java_lang_Thread::threadGroup(thread_obj); 3013 if (thread_group != NULL) { 3014 // ThreadGroup.name can be null 3015 return java_lang_ThreadGroup::name(thread_group); 3016 } 3017 } 3018 return NULL; 3019 } 3020 3021 const char* JavaThread::get_parent_name() const { 3022 debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);) 3023 oop thread_obj = threadObj(); 3024 if (thread_obj != NULL) { 3025 oop thread_group = java_lang_Thread::threadGroup(thread_obj); 3026 if (thread_group != NULL) { 3027 oop parent = java_lang_ThreadGroup::parent(thread_group); 3028 if (parent != NULL) { 3029 // ThreadGroup.name can be null 3030 return java_lang_ThreadGroup::name(parent); 3031 } 3032 } 3033 } 3034 return NULL; 3035 } 3036 3037 ThreadPriority JavaThread::java_priority() const { 3038 oop thr_oop = threadObj(); 3039 if (thr_oop == NULL) return NormPriority; // Bootstrapping 3040 ThreadPriority priority = java_lang_Thread::priority(thr_oop); 3041 assert(MinPriority <= priority && priority <= MaxPriority, "sanity check"); 3042 return priority; 3043 } 3044 3045 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) { 3046 3047 assert(Threads_lock->owner() == Thread::current(), "must have threads lock"); 3048 // Link Java Thread object <-> C++ Thread 3049 3050 // Get the C++ thread object (an oop) from the JNI handle (a jthread) 3051 // and put it into a new Handle. The Handle "thread_oop" can then 3052 // be used to pass the C++ thread object to other methods. 3053 3054 // Set the Java level thread object (jthread) field of the 3055 // new thread (a JavaThread *) to C++ thread object using the 3056 // "thread_oop" handle. 3057 3058 // Set the thread field (a JavaThread *) of the 3059 // oop representing the java_lang_Thread to the new thread (a JavaThread *). 3060 3061 Handle thread_oop(Thread::current(), 3062 JNIHandles::resolve_non_null(jni_thread)); 3063 assert(InstanceKlass::cast(thread_oop->klass())->is_linked(), 3064 "must be initialized"); 3065 set_threadObj(thread_oop()); 3066 java_lang_Thread::set_thread(thread_oop(), this); 3067 3068 if (prio == NoPriority) { 3069 prio = java_lang_Thread::priority(thread_oop()); 3070 assert(prio != NoPriority, "A valid priority should be present"); 3071 } 3072 3073 // Push the Java priority down to the native thread; needs Threads_lock 3074 Thread::set_priority(this, prio); 3075 3076 // Add the new thread to the Threads list and set it in motion. 3077 // We must have threads lock in order to call Threads::add. 3078 // It is crucial that we do not block before the thread is 3079 // added to the Threads list for if a GC happens, then the java_thread oop 3080 // will not be visited by GC. 3081 Threads::add(this); 3082 } 3083 3084 oop JavaThread::current_park_blocker() { 3085 // Support for JSR-166 locks 3086 oop thread_oop = threadObj(); 3087 if (thread_oop != NULL && 3088 JDK_Version::current().supports_thread_park_blocker()) { 3089 return java_lang_Thread::park_blocker(thread_oop); 3090 } 3091 return NULL; 3092 } 3093 3094 3095 void JavaThread::print_stack_on(outputStream* st) { 3096 if (!has_last_Java_frame()) return; 3097 ResourceMark rm; 3098 HandleMark hm; 3099 3100 RegisterMap reg_map(this); 3101 vframe* start_vf = last_java_vframe(®_map); 3102 int count = 0; 3103 for (vframe* f = start_vf; f != NULL; f = f->sender()) { 3104 if (f->is_java_frame()) { 3105 javaVFrame* jvf = javaVFrame::cast(f); 3106 java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci()); 3107 3108 // Print out lock information 3109 if (JavaMonitorsInStackTrace) { 3110 jvf->print_lock_info_on(st, count); 3111 } 3112 } else { 3113 // Ignore non-Java frames 3114 } 3115 3116 // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0 3117 count++; 3118 if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return; 3119 } 3120 } 3121 3122 3123 // JVMTI PopFrame support 3124 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) { 3125 assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments"); 3126 if (in_bytes(size_in_bytes) != 0) { 3127 _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread); 3128 _popframe_preserved_args_size = in_bytes(size_in_bytes); 3129 Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size); 3130 } 3131 } 3132 3133 void* JavaThread::popframe_preserved_args() { 3134 return _popframe_preserved_args; 3135 } 3136 3137 ByteSize JavaThread::popframe_preserved_args_size() { 3138 return in_ByteSize(_popframe_preserved_args_size); 3139 } 3140 3141 WordSize JavaThread::popframe_preserved_args_size_in_words() { 3142 int sz = in_bytes(popframe_preserved_args_size()); 3143 assert(sz % wordSize == 0, "argument size must be multiple of wordSize"); 3144 return in_WordSize(sz / wordSize); 3145 } 3146 3147 void JavaThread::popframe_free_preserved_args() { 3148 assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice"); 3149 FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args); 3150 _popframe_preserved_args = NULL; 3151 _popframe_preserved_args_size = 0; 3152 } 3153 3154 #ifndef PRODUCT 3155 3156 void JavaThread::trace_frames() { 3157 tty->print_cr("[Describe stack]"); 3158 int frame_no = 1; 3159 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 3160 tty->print(" %d. ", frame_no++); 3161 fst.current()->print_value_on(tty, this); 3162 tty->cr(); 3163 } 3164 } 3165 3166 class PrintAndVerifyOopClosure: public OopClosure { 3167 protected: 3168 template <class T> inline void do_oop_work(T* p) { 3169 oop obj = RawAccess<>::oop_load(p); 3170 if (obj == NULL) return; 3171 tty->print(INTPTR_FORMAT ": ", p2i(p)); 3172 if (oopDesc::is_oop_or_null(obj)) { 3173 if (obj->is_objArray()) { 3174 tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj)); 3175 } else { 3176 obj->print(); 3177 } 3178 } else { 3179 tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj)); 3180 } 3181 tty->cr(); 3182 } 3183 public: 3184 virtual void do_oop(oop* p) { do_oop_work(p); } 3185 virtual void do_oop(narrowOop* p) { do_oop_work(p); } 3186 }; 3187 3188 3189 static void oops_print(frame* f, const RegisterMap *map) { 3190 PrintAndVerifyOopClosure print; 3191 f->print_value(); 3192 f->oops_do(&print, NULL, (RegisterMap*)map); 3193 } 3194 3195 // Print our all the locations that contain oops and whether they are 3196 // valid or not. This useful when trying to find the oldest frame 3197 // where an oop has gone bad since the frame walk is from youngest to 3198 // oldest. 3199 void JavaThread::trace_oops() { 3200 tty->print_cr("[Trace oops]"); 3201 frames_do(oops_print); 3202 } 3203 3204 3205 #ifdef ASSERT 3206 // Print or validate the layout of stack frames 3207 void JavaThread::print_frame_layout(int depth, bool validate_only) { 3208 ResourceMark rm; 3209 PRESERVE_EXCEPTION_MARK; 3210 FrameValues values; 3211 int frame_no = 0; 3212 for (StackFrameStream fst(this, false); !fst.is_done(); fst.next()) { 3213 fst.current()->describe(values, ++frame_no); 3214 if (depth == frame_no) break; 3215 } 3216 if (validate_only) { 3217 values.validate(); 3218 } else { 3219 tty->print_cr("[Describe stack layout]"); 3220 values.print(this); 3221 } 3222 } 3223 #endif 3224 3225 void JavaThread::trace_stack_from(vframe* start_vf) { 3226 ResourceMark rm; 3227 int vframe_no = 1; 3228 for (vframe* f = start_vf; f; f = f->sender()) { 3229 if (f->is_java_frame()) { 3230 javaVFrame::cast(f)->print_activation(vframe_no++); 3231 } else { 3232 f->print(); 3233 } 3234 if (vframe_no > StackPrintLimit) { 3235 tty->print_cr("...<more frames>..."); 3236 return; 3237 } 3238 } 3239 } 3240 3241 3242 void JavaThread::trace_stack() { 3243 if (!has_last_Java_frame()) return; 3244 ResourceMark rm; 3245 HandleMark hm; 3246 RegisterMap reg_map(this); 3247 trace_stack_from(last_java_vframe(®_map)); 3248 } 3249 3250 3251 #endif // PRODUCT 3252 3253 3254 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) { 3255 assert(reg_map != NULL, "a map must be given"); 3256 frame f = last_frame(); 3257 for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) { 3258 if (vf->is_java_frame()) return javaVFrame::cast(vf); 3259 } 3260 return NULL; 3261 } 3262 3263 3264 Klass* JavaThread::security_get_caller_class(int depth) { 3265 vframeStream vfst(this); 3266 vfst.security_get_caller_frame(depth); 3267 if (!vfst.at_end()) { 3268 return vfst.method()->method_holder(); 3269 } 3270 return NULL; 3271 } 3272 3273 static void compiler_thread_entry(JavaThread* thread, TRAPS) { 3274 assert(thread->is_Compiler_thread(), "must be compiler thread"); 3275 CompileBroker::compiler_thread_loop(); 3276 } 3277 3278 static void sweeper_thread_entry(JavaThread* thread, TRAPS) { 3279 NMethodSweeper::sweeper_loop(); 3280 } 3281 3282 // Create a CompilerThread 3283 CompilerThread::CompilerThread(CompileQueue* queue, 3284 CompilerCounters* counters) 3285 : JavaThread(&compiler_thread_entry) { 3286 _env = NULL; 3287 _log = NULL; 3288 _task = NULL; 3289 _queue = queue; 3290 _counters = counters; 3291 _buffer_blob = NULL; 3292 _compiler = NULL; 3293 3294 // Compiler uses resource area for compilation, let's bias it to mtCompiler 3295 resource_area()->bias_to(mtCompiler); 3296 3297 #ifndef PRODUCT 3298 _ideal_graph_printer = NULL; 3299 #endif 3300 } 3301 3302 CompilerThread::~CompilerThread() { 3303 // Free buffer blob, if allocated 3304 if (get_buffer_blob() != NULL) { 3305 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 3306 CodeCache::free(get_buffer_blob()); 3307 } 3308 // Delete objects which were allocated on heap. 3309 delete _counters; 3310 } 3311 3312 bool CompilerThread::can_call_java() const { 3313 return _compiler != NULL && _compiler->is_jvmci(); 3314 } 3315 3316 // Create sweeper thread 3317 CodeCacheSweeperThread::CodeCacheSweeperThread() 3318 : JavaThread(&sweeper_thread_entry) { 3319 _scanned_compiled_method = NULL; 3320 } 3321 3322 void CodeCacheSweeperThread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 3323 JavaThread::oops_do(f, cf); 3324 if (_scanned_compiled_method != NULL && cf != NULL) { 3325 // Safepoints can occur when the sweeper is scanning an nmethod so 3326 // process it here to make sure it isn't unloaded in the middle of 3327 // a scan. 3328 cf->do_code_blob(_scanned_compiled_method); 3329 } 3330 } 3331 3332 void CodeCacheSweeperThread::nmethods_do(CodeBlobClosure* cf) { 3333 JavaThread::nmethods_do(cf); 3334 if (_scanned_compiled_method != NULL && cf != NULL) { 3335 // Safepoints can occur when the sweeper is scanning an nmethod so 3336 // process it here to make sure it isn't unloaded in the middle of 3337 // a scan. 3338 cf->do_code_blob(_scanned_compiled_method); 3339 } 3340 } 3341 3342 3343 // ======= Threads ======== 3344 3345 // The Threads class links together all active threads, and provides 3346 // operations over all threads. It is protected by the Threads_lock, 3347 // which is also used in other global contexts like safepointing. 3348 // ThreadsListHandles are used to safely perform operations on one 3349 // or more threads without the risk of the thread exiting during the 3350 // operation. 3351 // 3352 // Note: The Threads_lock is currently more widely used than we 3353 // would like. We are actively migrating Threads_lock uses to other 3354 // mechanisms in order to reduce Threads_lock contention. 3355 3356 JavaThread* Threads::_thread_list = NULL; 3357 int Threads::_number_of_threads = 0; 3358 int Threads::_number_of_non_daemon_threads = 0; 3359 int Threads::_return_code = 0; 3360 int Threads::_thread_claim_parity = 0; 3361 size_t JavaThread::_stack_size_at_create = 0; 3362 3363 #ifdef ASSERT 3364 bool Threads::_vm_complete = false; 3365 #endif 3366 3367 static inline void *prefetch_and_load_ptr(void **addr, intx prefetch_interval) { 3368 Prefetch::read((void*)addr, prefetch_interval); 3369 return *addr; 3370 } 3371 3372 // Possibly the ugliest for loop the world has seen. C++ does not allow 3373 // multiple types in the declaration section of the for loop. In this case 3374 // we are only dealing with pointers and hence can cast them. It looks ugly 3375 // but macros are ugly and therefore it's fine to make things absurdly ugly. 3376 #define DO_JAVA_THREADS(LIST, X) \ 3377 for (JavaThread *MACRO_scan_interval = (JavaThread*)(uintptr_t)PrefetchScanIntervalInBytes, \ 3378 *MACRO_list = (JavaThread*)(LIST), \ 3379 **MACRO_end = ((JavaThread**)((ThreadsList*)MACRO_list)->threads()) + ((ThreadsList*)MACRO_list)->length(), \ 3380 **MACRO_current_p = (JavaThread**)((ThreadsList*)MACRO_list)->threads(), \ 3381 *X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval); \ 3382 MACRO_current_p != MACRO_end; \ 3383 MACRO_current_p++, \ 3384 X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval)) 3385 3386 // All JavaThreads 3387 #define ALL_JAVA_THREADS(X) DO_JAVA_THREADS(ThreadsSMRSupport::get_java_thread_list(), X) 3388 3389 // All non-JavaThreads (i.e., every non-JavaThread in the system). 3390 void Threads::non_java_threads_do(ThreadClosure* tc) { 3391 // Someday we could have a table or list of all non-JavaThreads. 3392 // For now, just manually iterate through them. 3393 tc->do_thread(VMThread::vm_thread()); 3394 if (Universe::heap() != NULL) { 3395 Universe::heap()->gc_threads_do(tc); 3396 } 3397 WatcherThread *wt = WatcherThread::watcher_thread(); 3398 // Strictly speaking, the following NULL check isn't sufficient to make sure 3399 // the data for WatcherThread is still valid upon being examined. However, 3400 // considering that WatchThread terminates when the VM is on the way to 3401 // exit at safepoint, the chance of the above is extremely small. The right 3402 // way to prevent termination of WatcherThread would be to acquire 3403 // Terminator_lock, but we can't do that without violating the lock rank 3404 // checking in some cases. 3405 if (wt != NULL) { 3406 tc->do_thread(wt); 3407 } 3408 3409 #if INCLUDE_JFR 3410 Thread* sampler_thread = Jfr::sampler_thread(); 3411 if (sampler_thread != NULL) { 3412 tc->do_thread(sampler_thread); 3413 } 3414 3415 #endif 3416 3417 // If CompilerThreads ever become non-JavaThreads, add them here 3418 } 3419 3420 // All JavaThreads 3421 void Threads::java_threads_do(ThreadClosure* tc) { 3422 assert_locked_or_safepoint(Threads_lock); 3423 // ALL_JAVA_THREADS iterates through all JavaThreads. 3424 ALL_JAVA_THREADS(p) { 3425 tc->do_thread(p); 3426 } 3427 } 3428 3429 void Threads::java_threads_and_vm_thread_do(ThreadClosure* tc) { 3430 assert_locked_or_safepoint(Threads_lock); 3431 java_threads_do(tc); 3432 tc->do_thread(VMThread::vm_thread()); 3433 } 3434 3435 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system). 3436 void Threads::threads_do(ThreadClosure* tc) { 3437 assert_locked_or_safepoint(Threads_lock); 3438 java_threads_do(tc); 3439 non_java_threads_do(tc); 3440 } 3441 3442 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) { 3443 int cp = Threads::thread_claim_parity(); 3444 ALL_JAVA_THREADS(p) { 3445 if (p->claim_oops_do(is_par, cp)) { 3446 tc->do_thread(p); 3447 } 3448 } 3449 VMThread* vmt = VMThread::vm_thread(); 3450 if (vmt->claim_oops_do(is_par, cp)) { 3451 tc->do_thread(vmt); 3452 } 3453 } 3454 3455 // The system initialization in the library has three phases. 3456 // 3457 // Phase 1: java.lang.System class initialization 3458 // java.lang.System is a primordial class loaded and initialized 3459 // by the VM early during startup. java.lang.System.<clinit> 3460 // only does registerNatives and keeps the rest of the class 3461 // initialization work later until thread initialization completes. 3462 // 3463 // System.initPhase1 initializes the system properties, the static 3464 // fields in, out, and err. Set up java signal handlers, OS-specific 3465 // system settings, and thread group of the main thread. 3466 static void call_initPhase1(TRAPS) { 3467 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 3468 JavaValue result(T_VOID); 3469 JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(), 3470 vmSymbols::void_method_signature(), CHECK); 3471 } 3472 3473 // Phase 2. Module system initialization 3474 // This will initialize the module system. Only java.base classes 3475 // can be loaded until phase 2 completes. 3476 // 3477 // Call System.initPhase2 after the compiler initialization and jsr292 3478 // classes get initialized because module initialization runs a lot of java 3479 // code, that for performance reasons, should be compiled. Also, this will 3480 // enable the startup code to use lambda and other language features in this 3481 // phase and onward. 3482 // 3483 // After phase 2, The VM will begin search classes from -Xbootclasspath/a. 3484 static void call_initPhase2(TRAPS) { 3485 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime)); 3486 3487 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 3488 3489 JavaValue result(T_INT); 3490 JavaCallArguments args; 3491 args.push_int(DisplayVMOutputToStderr); 3492 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown 3493 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(), 3494 vmSymbols::boolean_boolean_int_signature(), &args, CHECK); 3495 if (result.get_jint() != JNI_OK) { 3496 vm_exit_during_initialization(); // no message or exception 3497 } 3498 3499 universe_post_module_init(); 3500 } 3501 3502 // Phase 3. final setup - set security manager, system class loader and TCCL 3503 // 3504 // This will instantiate and set the security manager, set the system class 3505 // loader as well as the thread context class loader. The security manager 3506 // and system class loader may be a custom class loaded from -Xbootclasspath/a, 3507 // other modules or the application's classpath. 3508 static void call_initPhase3(TRAPS) { 3509 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 3510 JavaValue result(T_VOID); 3511 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(), 3512 vmSymbols::void_method_signature(), CHECK); 3513 } 3514 3515 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) { 3516 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime)); 3517 3518 if (EagerXrunInit && Arguments::init_libraries_at_startup()) { 3519 create_vm_init_libraries(); 3520 } 3521 3522 initialize_class(vmSymbols::java_lang_String(), CHECK); 3523 3524 // Inject CompactStrings value after the static initializers for String ran. 3525 java_lang_String::set_compact_strings(CompactStrings); 3526 3527 // Initialize java_lang.System (needed before creating the thread) 3528 initialize_class(vmSymbols::java_lang_System(), CHECK); 3529 // The VM creates & returns objects of this class. Make sure it's initialized. 3530 initialize_class(vmSymbols::java_lang_Class(), CHECK); 3531 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK); 3532 Handle thread_group = create_initial_thread_group(CHECK); 3533 Universe::set_main_thread_group(thread_group()); 3534 initialize_class(vmSymbols::java_lang_Thread(), CHECK); 3535 oop thread_object = create_initial_thread(thread_group, main_thread, CHECK); 3536 main_thread->set_threadObj(thread_object); 3537 // Set thread status to running since main thread has 3538 // been started and running. 3539 java_lang_Thread::set_thread_status(thread_object, 3540 java_lang_Thread::RUNNABLE); 3541 3542 // The VM creates objects of this class. 3543 initialize_class(vmSymbols::java_lang_Module(), CHECK); 3544 3545 // The VM preresolves methods to these classes. Make sure that they get initialized 3546 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK); 3547 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK); 3548 3549 // Phase 1 of the system initialization in the library, java.lang.System class initialization 3550 call_initPhase1(CHECK); 3551 3552 // get the Java runtime name after java.lang.System is initialized 3553 JDK_Version::set_runtime_name(get_java_runtime_name(THREAD)); 3554 JDK_Version::set_runtime_version(get_java_runtime_version(THREAD)); 3555 3556 // an instance of OutOfMemory exception has been allocated earlier 3557 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK); 3558 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK); 3559 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK); 3560 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK); 3561 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK); 3562 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK); 3563 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK); 3564 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK); 3565 } 3566 3567 void Threads::initialize_jsr292_core_classes(TRAPS) { 3568 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime)); 3569 3570 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK); 3571 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK); 3572 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK); 3573 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK); 3574 } 3575 3576 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { 3577 extern void JDK_Version_init(); 3578 3579 // Preinitialize version info. 3580 VM_Version::early_initialize(); 3581 3582 // Check version 3583 if (!is_supported_jni_version(args->version)) return JNI_EVERSION; 3584 3585 // Initialize library-based TLS 3586 ThreadLocalStorage::init(); 3587 3588 // Initialize the output stream module 3589 ostream_init(); 3590 3591 // Process java launcher properties. 3592 Arguments::process_sun_java_launcher_properties(args); 3593 3594 // Initialize the os module 3595 os::init(); 3596 3597 // Record VM creation timing statistics 3598 TraceVmCreationTime create_vm_timer; 3599 create_vm_timer.start(); 3600 3601 // Initialize system properties. 3602 Arguments::init_system_properties(); 3603 3604 // So that JDK version can be used as a discriminator when parsing arguments 3605 JDK_Version_init(); 3606 3607 // Update/Initialize System properties after JDK version number is known 3608 Arguments::init_version_specific_system_properties(); 3609 3610 // Make sure to initialize log configuration *before* parsing arguments 3611 LogConfiguration::initialize(create_vm_timer.begin_time()); 3612 3613 // Parse arguments 3614 // Note: this internally calls os::init_container_support() 3615 jint parse_result = Arguments::parse(args); 3616 if (parse_result != JNI_OK) return parse_result; 3617 3618 os::init_before_ergo(); 3619 3620 jint ergo_result = Arguments::apply_ergo(); 3621 if (ergo_result != JNI_OK) return ergo_result; 3622 3623 // Final check of all ranges after ergonomics which may change values. 3624 if (!JVMFlagRangeList::check_ranges()) { 3625 return JNI_EINVAL; 3626 } 3627 3628 // Final check of all 'AfterErgo' constraints after ergonomics which may change values. 3629 bool constraint_result = JVMFlagConstraintList::check_constraints(JVMFlagConstraint::AfterErgo); 3630 if (!constraint_result) { 3631 return JNI_EINVAL; 3632 } 3633 3634 JVMFlagWriteableList::mark_startup(); 3635 3636 if (PauseAtStartup) { 3637 os::pause(); 3638 } 3639 3640 HOTSPOT_VM_INIT_BEGIN(); 3641 3642 // Timing (must come after argument parsing) 3643 TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime)); 3644 3645 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT 3646 // Initialize assert poison page mechanism. 3647 if (ShowRegistersOnAssert) { 3648 initialize_assert_poison(); 3649 } 3650 #endif // CAN_SHOW_REGISTERS_ON_ASSERT 3651 3652 // Initialize the os module after parsing the args 3653 jint os_init_2_result = os::init_2(); 3654 if (os_init_2_result != JNI_OK) return os_init_2_result; 3655 3656 SafepointMechanism::initialize(); 3657 3658 jint adjust_after_os_result = Arguments::adjust_after_os(); 3659 if (adjust_after_os_result != JNI_OK) return adjust_after_os_result; 3660 3661 // Initialize output stream logging 3662 ostream_init_log(); 3663 3664 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad 3665 // Must be before create_vm_init_agents() 3666 if (Arguments::init_libraries_at_startup()) { 3667 convert_vm_init_libraries_to_agents(); 3668 } 3669 3670 // Launch -agentlib/-agentpath and converted -Xrun agents 3671 if (Arguments::init_agents_at_startup()) { 3672 create_vm_init_agents(); 3673 } 3674 3675 // Initialize Threads state 3676 _thread_list = NULL; 3677 _number_of_threads = 0; 3678 _number_of_non_daemon_threads = 0; 3679 3680 // Initialize global data structures and create system classes in heap 3681 vm_init_globals(); 3682 3683 #if INCLUDE_JVMCI 3684 if (JVMCICounterSize > 0) { 3685 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal); 3686 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize); 3687 } else { 3688 JavaThread::_jvmci_old_thread_counters = NULL; 3689 } 3690 #endif // INCLUDE_JVMCI 3691 3692 // Attach the main thread to this os thread 3693 JavaThread* main_thread = new JavaThread(); 3694 main_thread->set_thread_state(_thread_in_vm); 3695 main_thread->initialize_thread_current(); 3696 // must do this before set_active_handles 3697 main_thread->record_stack_base_and_size(); 3698 main_thread->set_active_handles(JNIHandleBlock::allocate_block()); 3699 3700 if (!main_thread->set_as_starting_thread()) { 3701 vm_shutdown_during_initialization( 3702 "Failed necessary internal allocation. Out of swap space"); 3703 main_thread->smr_delete(); 3704 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 3705 return JNI_ENOMEM; 3706 } 3707 3708 // Enable guard page *after* os::create_main_thread(), otherwise it would 3709 // crash Linux VM, see notes in os_linux.cpp. 3710 main_thread->create_stack_guard_pages(); 3711 3712 // Initialize Java-Level synchronization subsystem 3713 ObjectMonitor::Initialize(); 3714 3715 // Initialize global modules 3716 jint status = init_globals(); 3717 if (status != JNI_OK) { 3718 main_thread->smr_delete(); 3719 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 3720 return status; 3721 } 3722 3723 JFR_ONLY(Jfr::on_vm_init();) 3724 3725 // Should be done after the heap is fully created 3726 main_thread->cache_global_variables(); 3727 3728 HandleMark hm; 3729 3730 { MutexLocker mu(Threads_lock); 3731 Threads::add(main_thread); 3732 } 3733 3734 // Any JVMTI raw monitors entered in onload will transition into 3735 // real raw monitor. VM is setup enough here for raw monitor enter. 3736 JvmtiExport::transition_pending_onload_raw_monitors(); 3737 3738 // Create the VMThread 3739 { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime)); 3740 3741 VMThread::create(); 3742 Thread* vmthread = VMThread::vm_thread(); 3743 3744 if (!os::create_thread(vmthread, os::vm_thread)) { 3745 vm_exit_during_initialization("Cannot create VM thread. " 3746 "Out of system resources."); 3747 } 3748 3749 // Wait for the VM thread to become ready, and VMThread::run to initialize 3750 // Monitors can have spurious returns, must always check another state flag 3751 { 3752 MutexLocker ml(Notify_lock); 3753 os::start_thread(vmthread); 3754 while (vmthread->active_handles() == NULL) { 3755 Notify_lock->wait(); 3756 } 3757 } 3758 } 3759 3760 assert(Universe::is_fully_initialized(), "not initialized"); 3761 if (VerifyDuringStartup) { 3762 // Make sure we're starting with a clean slate. 3763 VM_Verify verify_op; 3764 VMThread::execute(&verify_op); 3765 } 3766 3767 // We need this to update the java.vm.info property in case any flags used 3768 // to initially define it have been changed. This is needed for both CDS and 3769 // AOT, since UseSharedSpaces and UseAOT may be changed after java.vm.info 3770 // is initially computed. See Abstract_VM_Version::vm_info_string(). 3771 // This update must happen before we initialize the java classes, but 3772 // after any initialization logic that might modify the flags. 3773 Arguments::update_vm_info_property(VM_Version::vm_info_string()); 3774 3775 Thread* THREAD = Thread::current(); 3776 3777 // Always call even when there are not JVMTI environments yet, since environments 3778 // may be attached late and JVMTI must track phases of VM execution 3779 JvmtiExport::enter_early_start_phase(); 3780 3781 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 3782 JvmtiExport::post_early_vm_start(); 3783 3784 initialize_java_lang_classes(main_thread, CHECK_JNI_ERR); 3785 3786 quicken_jni_functions(); 3787 3788 // No more stub generation allowed after that point. 3789 StubCodeDesc::freeze(); 3790 3791 // Set flag that basic initialization has completed. Used by exceptions and various 3792 // debug stuff, that does not work until all basic classes have been initialized. 3793 set_init_completed(); 3794 3795 LogConfiguration::post_initialize(); 3796 Metaspace::post_initialize(); 3797 3798 HOTSPOT_VM_INIT_END(); 3799 3800 // record VM initialization completion time 3801 #if INCLUDE_MANAGEMENT 3802 Management::record_vm_init_completed(); 3803 #endif // INCLUDE_MANAGEMENT 3804 3805 // Signal Dispatcher needs to be started before VMInit event is posted 3806 os::initialize_jdk_signal_support(CHECK_JNI_ERR); 3807 3808 // Start Attach Listener if +StartAttachListener or it can't be started lazily 3809 if (!DisableAttachMechanism) { 3810 AttachListener::vm_start(); 3811 if (StartAttachListener || AttachListener::init_at_startup()) { 3812 AttachListener::init(); 3813 } 3814 } 3815 3816 // Launch -Xrun agents 3817 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP 3818 // back-end can launch with -Xdebug -Xrunjdwp. 3819 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) { 3820 create_vm_init_libraries(); 3821 } 3822 3823 if (CleanChunkPoolAsync) { 3824 Chunk::start_chunk_pool_cleaner_task(); 3825 } 3826 3827 // initialize compiler(s) 3828 #if defined(COMPILER1) || COMPILER2_OR_JVMCI 3829 #if INCLUDE_JVMCI 3830 bool force_JVMCI_intialization = false; 3831 if (EnableJVMCI) { 3832 // Initialize JVMCI eagerly when it is explicitly requested. 3833 // Or when JVMCIPrintProperties is enabled. 3834 // The JVMCI Java initialization code will read this flag and 3835 // do the printing if it's set. 3836 force_JVMCI_intialization = EagerJVMCI || JVMCIPrintProperties; 3837 3838 if (!force_JVMCI_intialization) { 3839 // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking 3840 // compilations via JVMCI will not actually block until JVMCI is initialized. 3841 force_JVMCI_intialization = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation); 3842 } 3843 } 3844 #endif 3845 CompileBroker::compilation_init_phase1(CHECK_JNI_ERR); 3846 // Postpone completion of compiler initialization to after JVMCI 3847 // is initialized to avoid timeouts of blocking compilations. 3848 if (JVMCI_ONLY(!force_JVMCI_intialization) NOT_JVMCI(true)) { 3849 CompileBroker::compilation_init_phase2(); 3850 } 3851 #endif 3852 3853 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading. 3854 // It is done after compilers are initialized, because otherwise compilations of 3855 // signature polymorphic MH intrinsics can be missed 3856 // (see SystemDictionary::find_method_handle_intrinsic). 3857 initialize_jsr292_core_classes(CHECK_JNI_ERR); 3858 3859 // This will initialize the module system. Only java.base classes can be 3860 // loaded until phase 2 completes 3861 call_initPhase2(CHECK_JNI_ERR); 3862 3863 // Always call even when there are not JVMTI environments yet, since environments 3864 // may be attached late and JVMTI must track phases of VM execution 3865 JvmtiExport::enter_start_phase(); 3866 3867 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 3868 JvmtiExport::post_vm_start(); 3869 3870 // Final system initialization including security manager and system class loader 3871 call_initPhase3(CHECK_JNI_ERR); 3872 3873 // cache the system and platform class loaders 3874 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR); 3875 3876 #if INCLUDE_CDS 3877 if (DumpSharedSpaces) { 3878 // capture the module path info from the ModuleEntryTable 3879 ClassLoader::initialize_module_path(THREAD); 3880 } 3881 #endif 3882 3883 #if INCLUDE_JVMCI 3884 if (force_JVMCI_intialization) { 3885 JVMCIRuntime::force_initialization(CHECK_JNI_ERR); 3886 CompileBroker::compilation_init_phase2(); 3887 } 3888 #endif 3889 3890 // Always call even when there are not JVMTI environments yet, since environments 3891 // may be attached late and JVMTI must track phases of VM execution 3892 JvmtiExport::enter_live_phase(); 3893 3894 // Notify JVMTI agents that VM initialization is complete - nop if no agents. 3895 JvmtiExport::post_vm_initialized(); 3896 3897 JFR_ONLY(Jfr::on_vm_start();) 3898 3899 #if INCLUDE_MANAGEMENT 3900 Management::initialize(THREAD); 3901 3902 if (HAS_PENDING_EXCEPTION) { 3903 // management agent fails to start possibly due to 3904 // configuration problem and is responsible for printing 3905 // stack trace if appropriate. Simply exit VM. 3906 vm_exit(1); 3907 } 3908 #endif // INCLUDE_MANAGEMENT 3909 3910 if (MemProfiling) MemProfiler::engage(); 3911 StatSampler::engage(); 3912 if (CheckJNICalls) JniPeriodicChecker::engage(); 3913 3914 BiasedLocking::init(); 3915 3916 #if INCLUDE_RTM_OPT 3917 RTMLockingCounters::init(); 3918 #endif 3919 3920 if (JDK_Version::current().post_vm_init_hook_enabled()) { 3921 call_postVMInitHook(THREAD); 3922 // The Java side of PostVMInitHook.run must deal with all 3923 // exceptions and provide means of diagnosis. 3924 if (HAS_PENDING_EXCEPTION) { 3925 CLEAR_PENDING_EXCEPTION; 3926 } 3927 } 3928 3929 { 3930 MutexLocker ml(PeriodicTask_lock); 3931 // Make sure the WatcherThread can be started by WatcherThread::start() 3932 // or by dynamic enrollment. 3933 WatcherThread::make_startable(); 3934 // Start up the WatcherThread if there are any periodic tasks 3935 // NOTE: All PeriodicTasks should be registered by now. If they 3936 // aren't, late joiners might appear to start slowly (we might 3937 // take a while to process their first tick). 3938 if (PeriodicTask::num_tasks() > 0) { 3939 WatcherThread::start(); 3940 } 3941 } 3942 3943 create_vm_timer.end(); 3944 #ifdef ASSERT 3945 _vm_complete = true; 3946 #endif 3947 3948 if (DumpSharedSpaces) { 3949 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR); 3950 ShouldNotReachHere(); 3951 } 3952 3953 return JNI_OK; 3954 } 3955 3956 // type for the Agent_OnLoad and JVM_OnLoad entry points 3957 extern "C" { 3958 typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *); 3959 } 3960 // Find a command line agent library and return its entry point for 3961 // -agentlib: -agentpath: -Xrun 3962 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array. 3963 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, 3964 const char *on_load_symbols[], 3965 size_t num_symbol_entries) { 3966 OnLoadEntry_t on_load_entry = NULL; 3967 void *library = NULL; 3968 3969 if (!agent->valid()) { 3970 char buffer[JVM_MAXPATHLEN]; 3971 char ebuf[1024] = ""; 3972 const char *name = agent->name(); 3973 const char *msg = "Could not find agent library "; 3974 3975 // First check to see if agent is statically linked into executable 3976 if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) { 3977 library = agent->os_lib(); 3978 } else if (agent->is_absolute_path()) { 3979 library = os::dll_load(name, ebuf, sizeof ebuf); 3980 if (library == NULL) { 3981 const char *sub_msg = " in absolute path, with error: "; 3982 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; 3983 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 3984 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 3985 // If we can't find the agent, exit. 3986 vm_exit_during_initialization(buf, NULL); 3987 FREE_C_HEAP_ARRAY(char, buf); 3988 } 3989 } else { 3990 // Try to load the agent from the standard dll directory 3991 if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(), 3992 name)) { 3993 library = os::dll_load(buffer, ebuf, sizeof ebuf); 3994 } 3995 if (library == NULL) { // Try the library path directory. 3996 if (os::dll_build_name(buffer, sizeof(buffer), name)) { 3997 library = os::dll_load(buffer, ebuf, sizeof ebuf); 3998 } 3999 if (library == NULL) { 4000 const char *sub_msg = " on the library path, with error: "; 4001 const char *sub_msg2 = "\nModule java.instrument may be missing from runtime image."; 4002 4003 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + 4004 strlen(ebuf) + strlen(sub_msg2) + 1; 4005 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 4006 if (!agent->is_instrument_lib()) { 4007 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 4008 } else { 4009 jio_snprintf(buf, len, "%s%s%s%s%s", msg, name, sub_msg, ebuf, sub_msg2); 4010 } 4011 // If we can't find the agent, exit. 4012 vm_exit_during_initialization(buf, NULL); 4013 FREE_C_HEAP_ARRAY(char, buf); 4014 } 4015 } 4016 } 4017 agent->set_os_lib(library); 4018 agent->set_valid(); 4019 } 4020 4021 // Find the OnLoad function. 4022 on_load_entry = 4023 CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent, 4024 false, 4025 on_load_symbols, 4026 num_symbol_entries)); 4027 return on_load_entry; 4028 } 4029 4030 // Find the JVM_OnLoad entry point 4031 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) { 4032 const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS; 4033 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 4034 } 4035 4036 // Find the Agent_OnLoad entry point 4037 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) { 4038 const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS; 4039 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 4040 } 4041 4042 // For backwards compatibility with -Xrun 4043 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be 4044 // treated like -agentpath: 4045 // Must be called before agent libraries are created 4046 void Threads::convert_vm_init_libraries_to_agents() { 4047 AgentLibrary* agent; 4048 AgentLibrary* next; 4049 4050 for (agent = Arguments::libraries(); agent != NULL; agent = next) { 4051 next = agent->next(); // cache the next agent now as this agent may get moved off this list 4052 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 4053 4054 // If there is an JVM_OnLoad function it will get called later, 4055 // otherwise see if there is an Agent_OnLoad 4056 if (on_load_entry == NULL) { 4057 on_load_entry = lookup_agent_on_load(agent); 4058 if (on_load_entry != NULL) { 4059 // switch it to the agent list -- so that Agent_OnLoad will be called, 4060 // JVM_OnLoad won't be attempted and Agent_OnUnload will 4061 Arguments::convert_library_to_agent(agent); 4062 } else { 4063 vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name()); 4064 } 4065 } 4066 } 4067 } 4068 4069 // Create agents for -agentlib: -agentpath: and converted -Xrun 4070 // Invokes Agent_OnLoad 4071 // Called very early -- before JavaThreads exist 4072 void Threads::create_vm_init_agents() { 4073 extern struct JavaVM_ main_vm; 4074 AgentLibrary* agent; 4075 4076 JvmtiExport::enter_onload_phase(); 4077 4078 for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 4079 OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent); 4080 4081 if (on_load_entry != NULL) { 4082 // Invoke the Agent_OnLoad function 4083 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 4084 if (err != JNI_OK) { 4085 vm_exit_during_initialization("agent library failed to init", agent->name()); 4086 } 4087 } else { 4088 vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name()); 4089 } 4090 } 4091 JvmtiExport::enter_primordial_phase(); 4092 } 4093 4094 extern "C" { 4095 typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *); 4096 } 4097 4098 void Threads::shutdown_vm_agents() { 4099 // Send any Agent_OnUnload notifications 4100 const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS; 4101 size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols); 4102 extern struct JavaVM_ main_vm; 4103 for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 4104 4105 // Find the Agent_OnUnload function. 4106 Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t, 4107 os::find_agent_function(agent, 4108 false, 4109 on_unload_symbols, 4110 num_symbol_entries)); 4111 4112 // Invoke the Agent_OnUnload function 4113 if (unload_entry != NULL) { 4114 JavaThread* thread = JavaThread::current(); 4115 ThreadToNativeFromVM ttn(thread); 4116 HandleMark hm(thread); 4117 (*unload_entry)(&main_vm); 4118 } 4119 } 4120 } 4121 4122 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries 4123 // Invokes JVM_OnLoad 4124 void Threads::create_vm_init_libraries() { 4125 extern struct JavaVM_ main_vm; 4126 AgentLibrary* agent; 4127 4128 for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) { 4129 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 4130 4131 if (on_load_entry != NULL) { 4132 // Invoke the JVM_OnLoad function 4133 JavaThread* thread = JavaThread::current(); 4134 ThreadToNativeFromVM ttn(thread); 4135 HandleMark hm(thread); 4136 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 4137 if (err != JNI_OK) { 4138 vm_exit_during_initialization("-Xrun library failed to init", agent->name()); 4139 } 4140 } else { 4141 vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name()); 4142 } 4143 } 4144 } 4145 4146 4147 // Last thread running calls java.lang.Shutdown.shutdown() 4148 void JavaThread::invoke_shutdown_hooks() { 4149 HandleMark hm(this); 4150 4151 // We could get here with a pending exception, if so clear it now. 4152 if (this->has_pending_exception()) { 4153 this->clear_pending_exception(); 4154 } 4155 4156 EXCEPTION_MARK; 4157 Klass* shutdown_klass = 4158 SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(), 4159 THREAD); 4160 if (shutdown_klass != NULL) { 4161 // SystemDictionary::resolve_or_null will return null if there was 4162 // an exception. If we cannot load the Shutdown class, just don't 4163 // call Shutdown.shutdown() at all. This will mean the shutdown hooks 4164 // won't be run. Note that if a shutdown hook was registered, 4165 // the Shutdown class would have already been loaded 4166 // (Runtime.addShutdownHook will load it). 4167 JavaValue result(T_VOID); 4168 JavaCalls::call_static(&result, 4169 shutdown_klass, 4170 vmSymbols::shutdown_method_name(), 4171 vmSymbols::void_method_signature(), 4172 THREAD); 4173 } 4174 CLEAR_PENDING_EXCEPTION; 4175 } 4176 4177 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when 4178 // the program falls off the end of main(). Another VM exit path is through 4179 // vm_exit() when the program calls System.exit() to return a value or when 4180 // there is a serious error in VM. The two shutdown paths are not exactly 4181 // the same, but they share Shutdown.shutdown() at Java level and before_exit() 4182 // and VM_Exit op at VM level. 4183 // 4184 // Shutdown sequence: 4185 // + Shutdown native memory tracking if it is on 4186 // + Wait until we are the last non-daemon thread to execute 4187 // <-- every thing is still working at this moment --> 4188 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level 4189 // shutdown hooks 4190 // + Call before_exit(), prepare for VM exit 4191 // > run VM level shutdown hooks (they are registered through JVM_OnExit(), 4192 // currently the only user of this mechanism is File.deleteOnExit()) 4193 // > stop StatSampler, watcher thread, CMS threads, 4194 // post thread end and vm death events to JVMTI, 4195 // stop signal thread 4196 // + Call JavaThread::exit(), it will: 4197 // > release JNI handle blocks, remove stack guard pages 4198 // > remove this thread from Threads list 4199 // <-- no more Java code from this thread after this point --> 4200 // + Stop VM thread, it will bring the remaining VM to a safepoint and stop 4201 // the compiler threads at safepoint 4202 // <-- do not use anything that could get blocked by Safepoint --> 4203 // + Disable tracing at JNI/JVM barriers 4204 // + Set _vm_exited flag for threads that are still running native code 4205 // + Delete this thread 4206 // + Call exit_globals() 4207 // > deletes tty 4208 // > deletes PerfMemory resources 4209 // + Return to caller 4210 4211 bool Threads::destroy_vm() { 4212 JavaThread* thread = JavaThread::current(); 4213 4214 #ifdef ASSERT 4215 _vm_complete = false; 4216 #endif 4217 // Wait until we are the last non-daemon thread to execute 4218 { MutexLocker nu(Threads_lock); 4219 while (Threads::number_of_non_daemon_threads() > 1) 4220 // This wait should make safepoint checks, wait without a timeout, 4221 // and wait as a suspend-equivalent condition. 4222 Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0, 4223 Mutex::_as_suspend_equivalent_flag); 4224 } 4225 4226 EventShutdown e; 4227 if (e.should_commit()) { 4228 e.set_reason("No remaining non-daemon Java threads"); 4229 e.commit(); 4230 } 4231 4232 // Hang forever on exit if we are reporting an error. 4233 if (ShowMessageBoxOnError && VMError::is_error_reported()) { 4234 os::infinite_sleep(); 4235 } 4236 os::wait_for_keypress_at_exit(); 4237 4238 // run Java level shutdown hooks 4239 thread->invoke_shutdown_hooks(); 4240 4241 before_exit(thread); 4242 4243 thread->exit(true); 4244 // thread will never call smr_delete, instead of implicit cancel 4245 // in wait_for_vm_thread_exit we do it explicit. 4246 thread->cancel_handshake(); 4247 4248 // Stop VM thread. 4249 { 4250 // 4945125 The vm thread comes to a safepoint during exit. 4251 // GC vm_operations can get caught at the safepoint, and the 4252 // heap is unparseable if they are caught. Grab the Heap_lock 4253 // to prevent this. The GC vm_operations will not be able to 4254 // queue until after the vm thread is dead. After this point, 4255 // we'll never emerge out of the safepoint before the VM exits. 4256 4257 MutexLocker ml(Heap_lock); 4258 4259 VMThread::wait_for_vm_thread_exit(); 4260 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint"); 4261 VMThread::destroy(); 4262 } 4263 4264 // Now, all Java threads are gone except daemon threads. Daemon threads 4265 // running Java code or in VM are stopped by the Safepoint. However, 4266 // daemon threads executing native code are still running. But they 4267 // will be stopped at native=>Java/VM barriers. Note that we can't 4268 // simply kill or suspend them, as it is inherently deadlock-prone. 4269 4270 VM_Exit::set_vm_exited(); 4271 4272 // Clean up ideal graph printers after the VMThread has started 4273 // the final safepoint which will block all the Compiler threads. 4274 // Note that this Thread has already logically exited so the 4275 // clean_up() function's use of a JavaThreadIteratorWithHandle 4276 // would be a problem except set_vm_exited() has remembered the 4277 // shutdown thread which is granted a policy exception. 4278 #if defined(COMPILER2) && !defined(PRODUCT) 4279 IdealGraphPrinter::clean_up(); 4280 #endif 4281 4282 notify_vm_shutdown(); 4283 4284 // We are after VM_Exit::set_vm_exited() so we can't call 4285 // thread->smr_delete() or we will block on the Threads_lock. 4286 // Deleting the shutdown thread here is safe because another 4287 // JavaThread cannot have an active ThreadsListHandle for 4288 // this JavaThread. 4289 delete thread; 4290 4291 #if INCLUDE_JVMCI 4292 if (JVMCICounterSize > 0) { 4293 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters); 4294 } 4295 #endif 4296 4297 // exit_globals() will delete tty 4298 exit_globals(); 4299 4300 LogConfiguration::finalize(); 4301 4302 return true; 4303 } 4304 4305 4306 jboolean Threads::is_supported_jni_version_including_1_1(jint version) { 4307 if (version == JNI_VERSION_1_1) return JNI_TRUE; 4308 return is_supported_jni_version(version); 4309 } 4310 4311 4312 jboolean Threads::is_supported_jni_version(jint version) { 4313 if (version == JNI_VERSION_1_2) return JNI_TRUE; 4314 if (version == JNI_VERSION_1_4) return JNI_TRUE; 4315 if (version == JNI_VERSION_1_6) return JNI_TRUE; 4316 if (version == JNI_VERSION_1_8) return JNI_TRUE; 4317 if (version == JNI_VERSION_9) return JNI_TRUE; 4318 if (version == JNI_VERSION_10) return JNI_TRUE; 4319 return JNI_FALSE; 4320 } 4321 4322 4323 void Threads::add(JavaThread* p, bool force_daemon) { 4324 // The threads lock must be owned at this point 4325 assert_locked_or_safepoint(Threads_lock); 4326 4327 BarrierSet::barrier_set()->on_thread_attach(p); 4328 4329 p->set_next(_thread_list); 4330 _thread_list = p; 4331 4332 // Once a JavaThread is added to the Threads list, smr_delete() has 4333 // to be used to delete it. Otherwise we can just delete it directly. 4334 p->set_on_thread_list(); 4335 4336 _number_of_threads++; 4337 oop threadObj = p->threadObj(); 4338 bool daemon = true; 4339 // Bootstrapping problem: threadObj can be null for initial 4340 // JavaThread (or for threads attached via JNI) 4341 if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) { 4342 _number_of_non_daemon_threads++; 4343 daemon = false; 4344 } 4345 4346 ThreadService::add_thread(p, daemon); 4347 4348 // Maintain fast thread list 4349 ThreadsSMRSupport::add_thread(p); 4350 4351 // Possible GC point. 4352 Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p)); 4353 } 4354 4355 void Threads::remove(JavaThread* p) { 4356 4357 // Reclaim the objectmonitors from the omInUseList and omFreeList of the moribund thread. 4358 ObjectSynchronizer::omFlush(p); 4359 4360 // Extra scope needed for Thread_lock, so we can check 4361 // that we do not remove thread without safepoint code notice 4362 { MutexLocker ml(Threads_lock); 4363 4364 assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present"); 4365 4366 // Maintain fast thread list 4367 ThreadsSMRSupport::remove_thread(p); 4368 4369 JavaThread* current = _thread_list; 4370 JavaThread* prev = NULL; 4371 4372 while (current != p) { 4373 prev = current; 4374 current = current->next(); 4375 } 4376 4377 if (prev) { 4378 prev->set_next(current->next()); 4379 } else { 4380 _thread_list = p->next(); 4381 } 4382 4383 _number_of_threads--; 4384 oop threadObj = p->threadObj(); 4385 bool daemon = true; 4386 if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) { 4387 _number_of_non_daemon_threads--; 4388 daemon = false; 4389 4390 // Only one thread left, do a notify on the Threads_lock so a thread waiting 4391 // on destroy_vm will wake up. 4392 if (number_of_non_daemon_threads() == 1) { 4393 Threads_lock->notify_all(); 4394 } 4395 } 4396 ThreadService::remove_thread(p, daemon); 4397 4398 // Make sure that safepoint code disregard this thread. This is needed since 4399 // the thread might mess around with locks after this point. This can cause it 4400 // to do callbacks into the safepoint code. However, the safepoint code is not aware 4401 // of this thread since it is removed from the queue. 4402 p->set_terminated_value(); 4403 } // unlock Threads_lock 4404 4405 // Since Events::log uses a lock, we grab it outside the Threads_lock 4406 Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p)); 4407 } 4408 4409 // Operations on the Threads list for GC. These are not explicitly locked, 4410 // but the garbage collector must provide a safe context for them to run. 4411 // In particular, these things should never be called when the Threads_lock 4412 // is held by some other thread. (Note: the Safepoint abstraction also 4413 // uses the Threads_lock to guarantee this property. It also makes sure that 4414 // all threads gets blocked when exiting or starting). 4415 4416 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) { 4417 ALL_JAVA_THREADS(p) { 4418 p->oops_do(f, cf); 4419 } 4420 VMThread::vm_thread()->oops_do(f, cf); 4421 } 4422 4423 void Threads::change_thread_claim_parity() { 4424 // Set the new claim parity. 4425 assert(_thread_claim_parity >= 0 && _thread_claim_parity <= 2, 4426 "Not in range."); 4427 _thread_claim_parity++; 4428 if (_thread_claim_parity == 3) _thread_claim_parity = 1; 4429 assert(_thread_claim_parity >= 1 && _thread_claim_parity <= 2, 4430 "Not in range."); 4431 } 4432 4433 #ifdef ASSERT 4434 void Threads::assert_all_threads_claimed() { 4435 ALL_JAVA_THREADS(p) { 4436 const int thread_parity = p->oops_do_parity(); 4437 assert((thread_parity == _thread_claim_parity), 4438 "Thread " PTR_FORMAT " has incorrect parity %d != %d", p2i(p), thread_parity, _thread_claim_parity); 4439 } 4440 VMThread* vmt = VMThread::vm_thread(); 4441 const int thread_parity = vmt->oops_do_parity(); 4442 assert((thread_parity == _thread_claim_parity), 4443 "VMThread " PTR_FORMAT " has incorrect parity %d != %d", p2i(vmt), thread_parity, _thread_claim_parity); 4444 } 4445 #endif // ASSERT 4446 4447 class ParallelOopsDoThreadClosure : public ThreadClosure { 4448 private: 4449 OopClosure* _f; 4450 CodeBlobClosure* _cf; 4451 public: 4452 ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {} 4453 void do_thread(Thread* t) { 4454 t->oops_do(_f, _cf); 4455 } 4456 }; 4457 4458 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) { 4459 ParallelOopsDoThreadClosure tc(f, cf); 4460 possibly_parallel_threads_do(is_par, &tc); 4461 } 4462 4463 void Threads::nmethods_do(CodeBlobClosure* cf) { 4464 ALL_JAVA_THREADS(p) { 4465 // This is used by the code cache sweeper to mark nmethods that are active 4466 // on the stack of a Java thread. Ignore the sweeper thread itself to avoid 4467 // marking CodeCacheSweeperThread::_scanned_compiled_method as active. 4468 if(!p->is_Code_cache_sweeper_thread()) { 4469 p->nmethods_do(cf); 4470 } 4471 } 4472 } 4473 4474 void Threads::metadata_do(void f(Metadata*)) { 4475 ALL_JAVA_THREADS(p) { 4476 p->metadata_do(f); 4477 } 4478 } 4479 4480 class ThreadHandlesClosure : public ThreadClosure { 4481 void (*_f)(Metadata*); 4482 public: 4483 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {} 4484 virtual void do_thread(Thread* thread) { 4485 thread->metadata_handles_do(_f); 4486 } 4487 }; 4488 4489 void Threads::metadata_handles_do(void f(Metadata*)) { 4490 // Only walk the Handles in Thread. 4491 ThreadHandlesClosure handles_closure(f); 4492 threads_do(&handles_closure); 4493 } 4494 4495 void Threads::deoptimized_wrt_marked_nmethods() { 4496 ALL_JAVA_THREADS(p) { 4497 p->deoptimized_wrt_marked_nmethods(); 4498 } 4499 } 4500 4501 4502 // Get count Java threads that are waiting to enter the specified monitor. 4503 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list, 4504 int count, 4505 address monitor) { 4506 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count); 4507 4508 int i = 0; 4509 DO_JAVA_THREADS(t_list, p) { 4510 if (!p->can_call_java()) continue; 4511 4512 address pending = (address)p->current_pending_monitor(); 4513 if (pending == monitor) { // found a match 4514 if (i < count) result->append(p); // save the first count matches 4515 i++; 4516 } 4517 } 4518 4519 return result; 4520 } 4521 4522 4523 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list, 4524 address owner) { 4525 // NULL owner means not locked so we can skip the search 4526 if (owner == NULL) return NULL; 4527 4528 DO_JAVA_THREADS(t_list, p) { 4529 // first, see if owner is the address of a Java thread 4530 if (owner == (address)p) return p; 4531 } 4532 4533 // Cannot assert on lack of success here since this function may be 4534 // used by code that is trying to report useful problem information 4535 // like deadlock detection. 4536 if (UseHeavyMonitors) return NULL; 4537 4538 // If we didn't find a matching Java thread and we didn't force use of 4539 // heavyweight monitors, then the owner is the stack address of the 4540 // Lock Word in the owning Java thread's stack. 4541 // 4542 JavaThread* the_owner = NULL; 4543 DO_JAVA_THREADS(t_list, q) { 4544 if (q->is_lock_owned(owner)) { 4545 the_owner = q; 4546 break; 4547 } 4548 } 4549 4550 // cannot assert on lack of success here; see above comment 4551 return the_owner; 4552 } 4553 4554 // Threads::print_on() is called at safepoint by VM_PrintThreads operation. 4555 void Threads::print_on(outputStream* st, bool print_stacks, 4556 bool internal_format, bool print_concurrent_locks, 4557 bool print_extended_info) { 4558 char buf[32]; 4559 st->print_raw_cr(os::local_time_string(buf, sizeof(buf))); 4560 4561 st->print_cr("Full thread dump %s (%s %s):", 4562 Abstract_VM_Version::vm_name(), 4563 Abstract_VM_Version::vm_release(), 4564 Abstract_VM_Version::vm_info_string()); 4565 st->cr(); 4566 4567 #if INCLUDE_SERVICES 4568 // Dump concurrent locks 4569 ConcurrentLocksDump concurrent_locks; 4570 if (print_concurrent_locks) { 4571 concurrent_locks.dump_at_safepoint(); 4572 } 4573 #endif // INCLUDE_SERVICES 4574 4575 ThreadsSMRSupport::print_info_on(st); 4576 st->cr(); 4577 4578 ALL_JAVA_THREADS(p) { 4579 ResourceMark rm; 4580 p->print_on(st, print_extended_info); 4581 if (print_stacks) { 4582 if (internal_format) { 4583 p->trace_stack(); 4584 } else { 4585 p->print_stack_on(st); 4586 } 4587 } 4588 st->cr(); 4589 #if INCLUDE_SERVICES 4590 if (print_concurrent_locks) { 4591 concurrent_locks.print_locks_on(p, st); 4592 } 4593 #endif // INCLUDE_SERVICES 4594 } 4595 4596 VMThread::vm_thread()->print_on(st); 4597 st->cr(); 4598 Universe::heap()->print_gc_threads_on(st); 4599 WatcherThread* wt = WatcherThread::watcher_thread(); 4600 if (wt != NULL) { 4601 wt->print_on(st); 4602 st->cr(); 4603 } 4604 4605 st->flush(); 4606 } 4607 4608 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf, 4609 int buflen, bool* found_current) { 4610 if (this_thread != NULL) { 4611 bool is_current = (current == this_thread); 4612 *found_current = *found_current || is_current; 4613 st->print("%s", is_current ? "=>" : " "); 4614 4615 st->print(PTR_FORMAT, p2i(this_thread)); 4616 st->print(" "); 4617 this_thread->print_on_error(st, buf, buflen); 4618 st->cr(); 4619 } 4620 } 4621 4622 class PrintOnErrorClosure : public ThreadClosure { 4623 outputStream* _st; 4624 Thread* _current; 4625 char* _buf; 4626 int _buflen; 4627 bool* _found_current; 4628 public: 4629 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf, 4630 int buflen, bool* found_current) : 4631 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {} 4632 4633 virtual void do_thread(Thread* thread) { 4634 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current); 4635 } 4636 }; 4637 4638 // Threads::print_on_error() is called by fatal error handler. It's possible 4639 // that VM is not at safepoint and/or current thread is inside signal handler. 4640 // Don't print stack trace, as the stack may not be walkable. Don't allocate 4641 // memory (even in resource area), it might deadlock the error handler. 4642 void Threads::print_on_error(outputStream* st, Thread* current, char* buf, 4643 int buflen) { 4644 ThreadsSMRSupport::print_info_on(st); 4645 st->cr(); 4646 4647 bool found_current = false; 4648 st->print_cr("Java Threads: ( => current thread )"); 4649 ALL_JAVA_THREADS(thread) { 4650 print_on_error(thread, st, current, buf, buflen, &found_current); 4651 } 4652 st->cr(); 4653 4654 st->print_cr("Other Threads:"); 4655 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current); 4656 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current); 4657 4658 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current); 4659 Universe::heap()->gc_threads_do(&print_closure); 4660 4661 if (!found_current) { 4662 st->cr(); 4663 st->print("=>" PTR_FORMAT " (exited) ", p2i(current)); 4664 current->print_on_error(st, buf, buflen); 4665 st->cr(); 4666 } 4667 st->cr(); 4668 4669 st->print_cr("Threads with active compile tasks:"); 4670 print_threads_compiling(st, buf, buflen); 4671 } 4672 4673 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen) { 4674 ALL_JAVA_THREADS(thread) { 4675 if (thread->is_Compiler_thread()) { 4676 CompilerThread* ct = (CompilerThread*) thread; 4677 4678 // Keep task in local variable for NULL check. 4679 // ct->_task might be set to NULL by concurring compiler thread 4680 // because it completed the compilation. The task is never freed, 4681 // though, just returned to a free list. 4682 CompileTask* task = ct->task(); 4683 if (task != NULL) { 4684 thread->print_name_on_error(st, buf, buflen); 4685 task->print(st, NULL, true, true); 4686 } 4687 } 4688 } 4689 } 4690 4691 4692 // Internal SpinLock and Mutex 4693 // Based on ParkEvent 4694 4695 // Ad-hoc mutual exclusion primitives: SpinLock and Mux 4696 // 4697 // We employ SpinLocks _only for low-contention, fixed-length 4698 // short-duration critical sections where we're concerned 4699 // about native mutex_t or HotSpot Mutex:: latency. 4700 // The mux construct provides a spin-then-block mutual exclusion 4701 // mechanism. 4702 // 4703 // Testing has shown that contention on the ListLock guarding gFreeList 4704 // is common. If we implement ListLock as a simple SpinLock it's common 4705 // for the JVM to devolve to yielding with little progress. This is true 4706 // despite the fact that the critical sections protected by ListLock are 4707 // extremely short. 4708 // 4709 // TODO-FIXME: ListLock should be of type SpinLock. 4710 // We should make this a 1st-class type, integrated into the lock 4711 // hierarchy as leaf-locks. Critically, the SpinLock structure 4712 // should have sufficient padding to avoid false-sharing and excessive 4713 // cache-coherency traffic. 4714 4715 4716 typedef volatile int SpinLockT; 4717 4718 void Thread::SpinAcquire(volatile int * adr, const char * LockName) { 4719 if (Atomic::cmpxchg (1, adr, 0) == 0) { 4720 return; // normal fast-path return 4721 } 4722 4723 // Slow-path : We've encountered contention -- Spin/Yield/Block strategy. 4724 TEVENT(SpinAcquire - ctx); 4725 int ctr = 0; 4726 int Yields = 0; 4727 for (;;) { 4728 while (*adr != 0) { 4729 ++ctr; 4730 if ((ctr & 0xFFF) == 0 || !os::is_MP()) { 4731 if (Yields > 5) { 4732 os::naked_short_sleep(1); 4733 } else { 4734 os::naked_yield(); 4735 ++Yields; 4736 } 4737 } else { 4738 SpinPause(); 4739 } 4740 } 4741 if (Atomic::cmpxchg(1, adr, 0) == 0) return; 4742 } 4743 } 4744 4745 void Thread::SpinRelease(volatile int * adr) { 4746 assert(*adr != 0, "invariant"); 4747 OrderAccess::fence(); // guarantee at least release consistency. 4748 // Roach-motel semantics. 4749 // It's safe if subsequent LDs and STs float "up" into the critical section, 4750 // but prior LDs and STs within the critical section can't be allowed 4751 // to reorder or float past the ST that releases the lock. 4752 // Loads and stores in the critical section - which appear in program 4753 // order before the store that releases the lock - must also appear 4754 // before the store that releases the lock in memory visibility order. 4755 // Conceptually we need a #loadstore|#storestore "release" MEMBAR before 4756 // the ST of 0 into the lock-word which releases the lock, so fence 4757 // more than covers this on all platforms. 4758 *adr = 0; 4759 } 4760 4761 // muxAcquire and muxRelease: 4762 // 4763 // * muxAcquire and muxRelease support a single-word lock-word construct. 4764 // The LSB of the word is set IFF the lock is held. 4765 // The remainder of the word points to the head of a singly-linked list 4766 // of threads blocked on the lock. 4767 // 4768 // * The current implementation of muxAcquire-muxRelease uses its own 4769 // dedicated Thread._MuxEvent instance. If we're interested in 4770 // minimizing the peak number of extant ParkEvent instances then 4771 // we could eliminate _MuxEvent and "borrow" _ParkEvent as long 4772 // as certain invariants were satisfied. Specifically, care would need 4773 // to be taken with regards to consuming unpark() "permits". 4774 // A safe rule of thumb is that a thread would never call muxAcquire() 4775 // if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently 4776 // park(). Otherwise the _ParkEvent park() operation in muxAcquire() could 4777 // consume an unpark() permit intended for monitorenter, for instance. 4778 // One way around this would be to widen the restricted-range semaphore 4779 // implemented in park(). Another alternative would be to provide 4780 // multiple instances of the PlatformEvent() for each thread. One 4781 // instance would be dedicated to muxAcquire-muxRelease, for instance. 4782 // 4783 // * Usage: 4784 // -- Only as leaf locks 4785 // -- for short-term locking only as muxAcquire does not perform 4786 // thread state transitions. 4787 // 4788 // Alternatives: 4789 // * We could implement muxAcquire and muxRelease with MCS or CLH locks 4790 // but with parking or spin-then-park instead of pure spinning. 4791 // * Use Taura-Oyama-Yonenzawa locks. 4792 // * It's possible to construct a 1-0 lock if we encode the lockword as 4793 // (List,LockByte). Acquire will CAS the full lockword while Release 4794 // will STB 0 into the LockByte. The 1-0 scheme admits stranding, so 4795 // acquiring threads use timers (ParkTimed) to detect and recover from 4796 // the stranding window. Thread/Node structures must be aligned on 256-byte 4797 // boundaries by using placement-new. 4798 // * Augment MCS with advisory back-link fields maintained with CAS(). 4799 // Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner. 4800 // The validity of the backlinks must be ratified before we trust the value. 4801 // If the backlinks are invalid the exiting thread must back-track through the 4802 // the forward links, which are always trustworthy. 4803 // * Add a successor indication. The LockWord is currently encoded as 4804 // (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable 4805 // to provide the usual futile-wakeup optimization. 4806 // See RTStt for details. 4807 // * Consider schedctl.sc_nopreempt to cover the critical section. 4808 // 4809 4810 4811 const intptr_t LOCKBIT = 1; 4812 4813 void Thread::muxAcquire(volatile intptr_t * Lock, const char * LockName) { 4814 intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0); 4815 if (w == 0) return; 4816 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4817 return; 4818 } 4819 4820 TEVENT(muxAcquire - Contention); 4821 ParkEvent * const Self = Thread::current()->_MuxEvent; 4822 assert((intptr_t(Self) & LOCKBIT) == 0, "invariant"); 4823 for (;;) { 4824 int its = (os::is_MP() ? 100 : 0) + 1; 4825 4826 // Optional spin phase: spin-then-park strategy 4827 while (--its >= 0) { 4828 w = *Lock; 4829 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4830 return; 4831 } 4832 } 4833 4834 Self->reset(); 4835 Self->OnList = intptr_t(Lock); 4836 // The following fence() isn't _strictly necessary as the subsequent 4837 // CAS() both serializes execution and ratifies the fetched *Lock value. 4838 OrderAccess::fence(); 4839 for (;;) { 4840 w = *Lock; 4841 if ((w & LOCKBIT) == 0) { 4842 if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4843 Self->OnList = 0; // hygiene - allows stronger asserts 4844 return; 4845 } 4846 continue; // Interference -- *Lock changed -- Just retry 4847 } 4848 assert(w & LOCKBIT, "invariant"); 4849 Self->ListNext = (ParkEvent *) (w & ~LOCKBIT); 4850 if (Atomic::cmpxchg(intptr_t(Self)|LOCKBIT, Lock, w) == w) break; 4851 } 4852 4853 while (Self->OnList != 0) { 4854 Self->park(); 4855 } 4856 } 4857 } 4858 4859 void Thread::muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev) { 4860 intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0); 4861 if (w == 0) return; 4862 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4863 return; 4864 } 4865 4866 TEVENT(muxAcquire - Contention); 4867 ParkEvent * ReleaseAfter = NULL; 4868 if (ev == NULL) { 4869 ev = ReleaseAfter = ParkEvent::Allocate(NULL); 4870 } 4871 assert((intptr_t(ev) & LOCKBIT) == 0, "invariant"); 4872 for (;;) { 4873 guarantee(ev->OnList == 0, "invariant"); 4874 int its = (os::is_MP() ? 100 : 0) + 1; 4875 4876 // Optional spin phase: spin-then-park strategy 4877 while (--its >= 0) { 4878 w = *Lock; 4879 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4880 if (ReleaseAfter != NULL) { 4881 ParkEvent::Release(ReleaseAfter); 4882 } 4883 return; 4884 } 4885 } 4886 4887 ev->reset(); 4888 ev->OnList = intptr_t(Lock); 4889 // The following fence() isn't _strictly necessary as the subsequent 4890 // CAS() both serializes execution and ratifies the fetched *Lock value. 4891 OrderAccess::fence(); 4892 for (;;) { 4893 w = *Lock; 4894 if ((w & LOCKBIT) == 0) { 4895 if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4896 ev->OnList = 0; 4897 // We call ::Release while holding the outer lock, thus 4898 // artificially lengthening the critical section. 4899 // Consider deferring the ::Release() until the subsequent unlock(), 4900 // after we've dropped the outer lock. 4901 if (ReleaseAfter != NULL) { 4902 ParkEvent::Release(ReleaseAfter); 4903 } 4904 return; 4905 } 4906 continue; // Interference -- *Lock changed -- Just retry 4907 } 4908 assert(w & LOCKBIT, "invariant"); 4909 ev->ListNext = (ParkEvent *) (w & ~LOCKBIT); 4910 if (Atomic::cmpxchg(intptr_t(ev)|LOCKBIT, Lock, w) == w) break; 4911 } 4912 4913 while (ev->OnList != 0) { 4914 ev->park(); 4915 } 4916 } 4917 } 4918 4919 // Release() must extract a successor from the list and then wake that thread. 4920 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme 4921 // similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based 4922 // Release() would : 4923 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list. 4924 // (B) Extract a successor from the private list "in-hand" 4925 // (C) attempt to CAS() the residual back into *Lock over null. 4926 // If there were any newly arrived threads and the CAS() would fail. 4927 // In that case Release() would detach the RATs, re-merge the list in-hand 4928 // with the RATs and repeat as needed. Alternately, Release() might 4929 // detach and extract a successor, but then pass the residual list to the wakee. 4930 // The wakee would be responsible for reattaching and remerging before it 4931 // competed for the lock. 4932 // 4933 // Both "pop" and DMR are immune from ABA corruption -- there can be 4934 // multiple concurrent pushers, but only one popper or detacher. 4935 // This implementation pops from the head of the list. This is unfair, 4936 // but tends to provide excellent throughput as hot threads remain hot. 4937 // (We wake recently run threads first). 4938 // 4939 // All paths through muxRelease() will execute a CAS. 4940 // Release consistency -- We depend on the CAS in muxRelease() to provide full 4941 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations 4942 // executed within the critical section are complete and globally visible before the 4943 // store (CAS) to the lock-word that releases the lock becomes globally visible. 4944 void Thread::muxRelease(volatile intptr_t * Lock) { 4945 for (;;) { 4946 const intptr_t w = Atomic::cmpxchg((intptr_t)0, Lock, LOCKBIT); 4947 assert(w & LOCKBIT, "invariant"); 4948 if (w == LOCKBIT) return; 4949 ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT); 4950 assert(List != NULL, "invariant"); 4951 assert(List->OnList == intptr_t(Lock), "invariant"); 4952 ParkEvent * const nxt = List->ListNext; 4953 guarantee((intptr_t(nxt) & LOCKBIT) == 0, "invariant"); 4954 4955 // The following CAS() releases the lock and pops the head element. 4956 // The CAS() also ratifies the previously fetched lock-word value. 4957 if (Atomic::cmpxchg(intptr_t(nxt), Lock, w) != w) { 4958 continue; 4959 } 4960 List->OnList = 0; 4961 OrderAccess::fence(); 4962 List->unpark(); 4963 return; 4964 } 4965 } 4966 4967 4968 void Threads::verify() { 4969 ALL_JAVA_THREADS(p) { 4970 p->verify(); 4971 } 4972 VMThread* thread = VMThread::vm_thread(); 4973 if (thread != NULL) thread->verify(); 4974 }