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