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