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