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