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