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