1 /*
   2  * Copyright (c) 1997, 2016, 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 #ifndef SHARE_VM_RUNTIME_THREAD_HPP
  26 #define SHARE_VM_RUNTIME_THREAD_HPP
  27 
  28 #include "gc/shared/threadLocalAllocBuffer.hpp"
  29 #include "memory/allocation.hpp"
  30 #include "oops/oop.hpp"
  31 #include "prims/jni.h"
  32 #include "prims/jvmtiExport.hpp"
  33 #include "runtime/frame.hpp"
  34 #include "runtime/javaFrameAnchor.hpp"
  35 #include "runtime/jniHandles.hpp"
  36 #include "runtime/mutexLocker.hpp"
  37 #include "runtime/os.hpp"
  38 #include "runtime/osThread.hpp"
  39 #include "runtime/park.hpp"
  40 #include "runtime/safepoint.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "runtime/threadLocalStorage.hpp"
  43 #include "runtime/thread_ext.hpp"
  44 #include "runtime/unhandledOops.hpp"
  45 #include "trace/traceBackend.hpp"
  46 #include "trace/traceMacros.hpp"
  47 #include "utilities/exceptions.hpp"
  48 #include "utilities/macros.hpp"
  49 #if INCLUDE_ALL_GCS
  50 #include "gc/g1/dirtyCardQueue.hpp"
  51 #include "gc/g1/satbMarkQueue.hpp"
  52 #endif // INCLUDE_ALL_GCS
  53 #ifdef ZERO
  54 # include "stack_zero.hpp"
  55 #endif
  56 
  57 class ThreadSafepointState;
  58 class ThreadProfiler;
  59 
  60 class JvmtiThreadState;
  61 class JvmtiGetLoadedClassesClosure;
  62 class ThreadStatistics;
  63 class ConcurrentLocksDump;
  64 class ParkEvent;
  65 class Parker;
  66 
  67 class ciEnv;
  68 class CompileThread;
  69 class CompileLog;
  70 class CompileTask;
  71 class CompileQueue;
  72 class CompilerCounters;
  73 class vframeArray;
  74 
  75 class DeoptResourceMark;
  76 class jvmtiDeferredLocalVariableSet;
  77 
  78 class GCTaskQueue;
  79 class ThreadClosure;
  80 class IdealGraphPrinter;
  81 
  82 class Metadata;
  83 template <class T, MEMFLAGS F> class ChunkedList;
  84 typedef ChunkedList<Metadata*, mtInternal> MetadataOnStackBuffer;
  85 
  86 DEBUG_ONLY(class ResourceMark;)
  87 
  88 class WorkerThread;
  89 
  90 // Class hierarchy
  91 // - Thread
  92 //   - NamedThread
  93 //     - VMThread
  94 //     - ConcurrentGCThread
  95 //     - WorkerThread
  96 //       - GangWorker
  97 //       - GCTaskThread
  98 //   - JavaThread
  99 //     - various subclasses eg CompilerThread, ServiceThread
 100 //   - WatcherThread
 101 
 102 class Thread: public ThreadShadow {
 103   friend class VMStructs;
 104   friend class JVMCIVMStructs;
 105  private:
 106 
 107 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 108   // Current thread is maintained as a thread-local variable
 109   static THREAD_LOCAL_DECL Thread* _thr_current;
 110 #endif
 111 
 112   // Exception handling
 113   // (Note: _pending_exception and friends are in ThreadShadow)
 114   //oop       _pending_exception;                // pending exception for current thread
 115   // const char* _exception_file;                   // file information for exception (debugging only)
 116   // int         _exception_line;                   // line information for exception (debugging only)
 117  protected:
 118   // Support for forcing alignment of thread objects for biased locking
 119   void*       _real_malloc_address;
 120  public:
 121   void* operator new(size_t size) throw() { return allocate(size, true); }
 122   void* operator new(size_t size, const std::nothrow_t& nothrow_constant) throw() {
 123     return allocate(size, false); }
 124   void  operator delete(void* p);
 125 
 126  protected:
 127   static void* allocate(size_t size, bool throw_excpt, MEMFLAGS flags = mtThread);
 128  private:
 129 
 130   // ***************************************************************
 131   // Suspend and resume support
 132   // ***************************************************************
 133   //
 134   // VM suspend/resume no longer exists - it was once used for various
 135   // things including safepoints but was deprecated and finally removed
 136   // in Java 7. Because VM suspension was considered "internal" Java-level
 137   // suspension was considered "external", and this legacy naming scheme
 138   // remains.
 139   //
 140   // External suspend/resume requests come from JVM_SuspendThread,
 141   // JVM_ResumeThread, JVMTI SuspendThread, and finally JVMTI
 142   // ResumeThread. External
 143   // suspend requests cause _external_suspend to be set and external
 144   // resume requests cause _external_suspend to be cleared.
 145   // External suspend requests do not nest on top of other external
 146   // suspend requests. The higher level APIs reject suspend requests
 147   // for already suspended threads.
 148   //
 149   // The external_suspend
 150   // flag is checked by has_special_runtime_exit_condition() and java thread
 151   // will self-suspend when handle_special_runtime_exit_condition() is
 152   // called. Most uses of the _thread_blocked state in JavaThreads are
 153   // considered the same as being externally suspended; if the blocking
 154   // condition lifts, the JavaThread will self-suspend. Other places
 155   // where VM checks for external_suspend include:
 156   //   + mutex granting (do not enter monitors when thread is suspended)
 157   //   + state transitions from _thread_in_native
 158   //
 159   // In general, java_suspend() does not wait for an external suspend
 160   // request to complete. When it returns, the only guarantee is that
 161   // the _external_suspend field is true.
 162   //
 163   // wait_for_ext_suspend_completion() is used to wait for an external
 164   // suspend request to complete. External suspend requests are usually
 165   // followed by some other interface call that requires the thread to
 166   // be quiescent, e.g., GetCallTrace(). By moving the "wait time" into
 167   // the interface that requires quiescence, we give the JavaThread a
 168   // chance to self-suspend before we need it to be quiescent. This
 169   // improves overall suspend/query performance.
 170   //
 171   // _suspend_flags controls the behavior of java_ suspend/resume.
 172   // It must be set under the protection of SR_lock. Read from the flag is
 173   // OK without SR_lock as long as the value is only used as a hint.
 174   // (e.g., check _external_suspend first without lock and then recheck
 175   // inside SR_lock and finish the suspension)
 176   //
 177   // _suspend_flags is also overloaded for other "special conditions" so
 178   // that a single check indicates whether any special action is needed
 179   // eg. for async exceptions.
 180   // -------------------------------------------------------------------
 181   // Notes:
 182   // 1. The suspend/resume logic no longer uses ThreadState in OSThread
 183   // but we still update its value to keep other part of the system (mainly
 184   // JVMTI) happy. ThreadState is legacy code (see notes in
 185   // osThread.hpp).
 186   //
 187   // 2. It would be more natural if set_external_suspend() is private and
 188   // part of java_suspend(), but that probably would affect the suspend/query
 189   // performance. Need more investigation on this.
 190 
 191   // suspend/resume lock: used for self-suspend
 192   Monitor* _SR_lock;
 193 
 194  protected:
 195   enum SuspendFlags {
 196     // NOTE: avoid using the sign-bit as cc generates different test code
 197     //       when the sign-bit is used, and sometimes incorrectly - see CR 6398077
 198 
 199     _external_suspend       = 0x20000000U, // thread is asked to self suspend
 200     _ext_suspended          = 0x40000000U, // thread has self-suspended
 201     _deopt_suspend          = 0x10000000U, // thread needs to self suspend for deopt
 202 
 203     _has_async_exception    = 0x00000001U, // there is a pending async exception
 204     _critical_native_unlock = 0x00000002U  // Must call back to unlock JNI critical lock
 205   };
 206 
 207   // various suspension related flags - atomically updated
 208   // overloaded for async exception checking in check_special_condition_for_native_trans.
 209   volatile uint32_t _suspend_flags;
 210 
 211  private:
 212   int _num_nested_signal;
 213 
 214   DEBUG_ONLY(bool _suspendible_thread;)
 215 
 216  public:
 217   void enter_signal_handler() { _num_nested_signal++; }
 218   void leave_signal_handler() { _num_nested_signal--; }
 219   bool is_inside_signal_handler() const { return _num_nested_signal > 0; }
 220 
 221 #ifdef ASSERT
 222   void set_suspendible_thread() {
 223     _suspendible_thread = true;
 224   }
 225 
 226   void clear_suspendible_thread() {
 227     _suspendible_thread = false;
 228   }
 229 
 230   bool is_suspendible_thread() { return _suspendible_thread; }
 231 #endif
 232 
 233  private:
 234   // Active_handles points to a block of handles
 235   JNIHandleBlock* _active_handles;
 236 
 237   // One-element thread local free list
 238   JNIHandleBlock* _free_handle_block;
 239 
 240   // Point to the last handle mark
 241   HandleMark* _last_handle_mark;
 242 
 243   // The parity of the last strong_roots iteration in which this thread was
 244   // claimed as a task.
 245   jint _oops_do_parity;
 246 
 247  public:
 248   void set_last_handle_mark(HandleMark* mark)   { _last_handle_mark = mark; }
 249   HandleMark* last_handle_mark() const          { return _last_handle_mark; }
 250  private:
 251 
 252   // debug support for checking if code does allow safepoints or not
 253   // GC points in the VM can happen because of allocation, invoking a VM operation, or blocking on
 254   // mutex, or blocking on an object synchronizer (Java locking).
 255   // If !allow_safepoint(), then an assertion failure will happen in any of the above cases
 256   // If !allow_allocation(), then an assertion failure will happen during allocation
 257   // (Hence, !allow_safepoint() => !allow_allocation()).
 258   //
 259   // The two classes NoSafepointVerifier and No_Allocation_Verifier are used to set these counters.
 260   //
 261   NOT_PRODUCT(int _allow_safepoint_count;)      // If 0, thread allow a safepoint to happen
 262   debug_only(int _allow_allocation_count;)     // If 0, the thread is allowed to allocate oops.
 263 
 264   // Used by SkipGCALot class.
 265   NOT_PRODUCT(bool _skip_gcalot;)               // Should we elide gc-a-lot?
 266 
 267   friend class NoAllocVerifier;
 268   friend class NoSafepointVerifier;
 269   friend class PauseNoSafepointVerifier;
 270   friend class GCLocker;
 271 
 272   ThreadLocalAllocBuffer _tlab;                 // Thread-local eden
 273   jlong _allocated_bytes;                       // Cumulative number of bytes allocated on
 274                                                 // the Java heap
 275 
 276   mutable TRACE_DATA _trace_data;               // Thread-local data for tracing
 277 
 278   ThreadExt _ext;
 279 
 280   int   _vm_operation_started_count;            // VM_Operation support
 281   int   _vm_operation_completed_count;          // VM_Operation support
 282 
 283   ObjectMonitor* _current_pending_monitor;      // ObjectMonitor this thread
 284                                                 // is waiting to lock
 285   bool _current_pending_monitor_is_from_java;   // locking is from Java code
 286 
 287   // ObjectMonitor on which this thread called Object.wait()
 288   ObjectMonitor* _current_waiting_monitor;
 289 
 290   // Private thread-local objectmonitor list - a simple cache organized as a SLL.
 291  public:
 292   ObjectMonitor* omFreeList;
 293   int omFreeCount;                              // length of omFreeList
 294   int omFreeProvision;                          // reload chunk size
 295   ObjectMonitor* omInUseList;                   // SLL to track monitors in circulation
 296   int omInUseCount;                             // length of omInUseList
 297 
 298 #ifdef ASSERT
 299  private:
 300   bool _visited_for_critical_count;
 301 
 302  public:
 303   void set_visited_for_critical_count(bool z) { _visited_for_critical_count = z; }
 304   bool was_visited_for_critical_count() const   { return _visited_for_critical_count; }
 305 #endif
 306 
 307  public:
 308   enum {
 309     is_definitely_current_thread = true
 310   };
 311 
 312   // Constructor
 313   Thread();
 314   virtual ~Thread();
 315 
 316   // Manage Thread::current()
 317   void initialize_thread_current();
 318   void clear_thread_current(); // TLS cleanup needed before threads terminate
 319 
 320   public:
 321   // thread entry point
 322   virtual void run();
 323 
 324   // Testers
 325   virtual bool is_VM_thread()       const            { return false; }
 326   virtual bool is_Java_thread()     const            { return false; }
 327   virtual bool is_Compiler_thread() const            { return false; }
 328   virtual bool is_Code_cache_sweeper_thread() const  { return false; }
 329   virtual bool is_hidden_from_external_view() const  { return false; }
 330   virtual bool is_jvmti_agent_thread() const         { return false; }
 331   // True iff the thread can perform GC operations at a safepoint.
 332   // Generally will be true only of VM thread and parallel GC WorkGang
 333   // threads.
 334   virtual bool is_GC_task_thread() const             { return false; }
 335   virtual bool is_Watcher_thread() const             { return false; }
 336   virtual bool is_ConcurrentGC_thread() const        { return false; }
 337   virtual bool is_Named_thread() const               { return false; }
 338   virtual bool is_Worker_thread() const              { return false; }
 339 
 340   // Can this thread make Java upcalls
 341   virtual bool can_call_java() const                 { return false; }
 342 
 343   // Casts
 344   virtual WorkerThread* as_Worker_thread() const     { return NULL; }
 345 
 346   virtual char* name() const { return (char*)"Unknown thread"; }
 347 
 348   // Returns the current thread (ASSERTS if NULL)
 349   static inline Thread* current();
 350   // Returns the current thread, or NULL if not attached
 351   static inline Thread* current_or_null();
 352   // Returns the current thread, or NULL if not attached, and is
 353   // safe for use from signal-handlers
 354   static inline Thread* current_or_null_safe();
 355 
 356   // Common thread operations
 357   static void set_priority(Thread* thread, ThreadPriority priority);
 358   static ThreadPriority get_priority(const Thread* const thread);
 359   static void start(Thread* thread);
 360   static void interrupt(Thread* thr);
 361   static bool is_interrupted(Thread* thr, bool clear_interrupted);
 362 
 363   void set_native_thread_name(const char *name) {
 364     assert(Thread::current() == this, "set_native_thread_name can only be called on the current thread");
 365     os::set_native_thread_name(name);
 366   }
 367 
 368   ObjectMonitor** omInUseList_addr()             { return (ObjectMonitor **)&omInUseList; }
 369   Monitor* SR_lock() const                       { return _SR_lock; }
 370 
 371   bool has_async_exception() const { return (_suspend_flags & _has_async_exception) != 0; }
 372 
 373   inline void set_suspend_flag(SuspendFlags f);
 374   inline void clear_suspend_flag(SuspendFlags f);
 375 
 376   inline void set_has_async_exception();
 377   inline void clear_has_async_exception();
 378 
 379   bool do_critical_native_unlock() const { return (_suspend_flags & _critical_native_unlock) != 0; }
 380 
 381   inline void set_critical_native_unlock();
 382   inline void clear_critical_native_unlock();
 383 
 384   // Support for Unhandled Oop detection
 385   // Add the field for both, fastdebug and debug, builds to keep
 386   // Thread's fields layout the same.
 387   // Note: CHECK_UNHANDLED_OOPS is defined only for fastdebug build.
 388 #ifdef CHECK_UNHANDLED_OOPS
 389  private:
 390   UnhandledOops* _unhandled_oops;
 391 #elif defined(ASSERT)
 392  private:
 393   void* _unhandled_oops;
 394 #endif
 395 #ifdef CHECK_UNHANDLED_OOPS
 396  public:
 397   UnhandledOops* unhandled_oops() { return _unhandled_oops; }
 398   // Mark oop safe for gc.  It may be stack allocated but won't move.
 399   void allow_unhandled_oop(oop *op) {
 400     if (CheckUnhandledOops) unhandled_oops()->allow_unhandled_oop(op);
 401   }
 402   // Clear oops at safepoint so crashes point to unhandled oop violator
 403   void clear_unhandled_oops() {
 404     if (CheckUnhandledOops) unhandled_oops()->clear_unhandled_oops();
 405   }
 406 #endif // CHECK_UNHANDLED_OOPS
 407 
 408  public:
 409 #ifndef PRODUCT
 410   bool skip_gcalot()           { return _skip_gcalot; }
 411   void set_skip_gcalot(bool v) { _skip_gcalot = v;    }
 412 #endif
 413 
 414   // Installs a pending exception to be inserted later
 415   static void send_async_exception(oop thread_oop, oop java_throwable);
 416 
 417   // Resource area
 418   ResourceArea* resource_area() const            { return _resource_area; }
 419   void set_resource_area(ResourceArea* area)     { _resource_area = area; }
 420 
 421   OSThread* osthread() const                     { return _osthread;   }
 422   void set_osthread(OSThread* thread)            { _osthread = thread; }
 423 
 424   // JNI handle support
 425   JNIHandleBlock* active_handles() const         { return _active_handles; }
 426   void set_active_handles(JNIHandleBlock* block) { _active_handles = block; }
 427   JNIHandleBlock* free_handle_block() const      { return _free_handle_block; }
 428   void set_free_handle_block(JNIHandleBlock* block) { _free_handle_block = block; }
 429 
 430   // Internal handle support
 431   HandleArea* handle_area() const                { return _handle_area; }
 432   void set_handle_area(HandleArea* area)         { _handle_area = area; }
 433 
 434   GrowableArray<Metadata*>* metadata_handles() const          { return _metadata_handles; }
 435   void set_metadata_handles(GrowableArray<Metadata*>* handles){ _metadata_handles = handles; }
 436 
 437   // Thread-Local Allocation Buffer (TLAB) support
 438   ThreadLocalAllocBuffer& tlab()                 { return _tlab; }
 439   void initialize_tlab() {
 440     if (UseTLAB) {
 441       tlab().initialize();
 442     }
 443   }
 444 
 445   jlong allocated_bytes()               { return _allocated_bytes; }
 446   void set_allocated_bytes(jlong value) { _allocated_bytes = value; }
 447   void incr_allocated_bytes(jlong size) { _allocated_bytes += size; }
 448   inline jlong cooked_allocated_bytes();
 449 
 450   TRACE_DEFINE_THREAD_TRACE_DATA_OFFSET;
 451   TRACE_DATA* trace_data() const        { return &_trace_data; }
 452 
 453   const ThreadExt& ext() const          { return _ext; }
 454   ThreadExt& ext()                      { return _ext; }
 455 
 456   // VM operation support
 457   int vm_operation_ticket()                      { return ++_vm_operation_started_count; }
 458   int vm_operation_completed_count()             { return _vm_operation_completed_count; }
 459   void increment_vm_operation_completed_count()  { _vm_operation_completed_count++; }
 460 
 461   // For tracking the heavyweight monitor the thread is pending on.
 462   ObjectMonitor* current_pending_monitor() {
 463     return _current_pending_monitor;
 464   }
 465   void set_current_pending_monitor(ObjectMonitor* monitor) {
 466     _current_pending_monitor = monitor;
 467   }
 468   void set_current_pending_monitor_is_from_java(bool from_java) {
 469     _current_pending_monitor_is_from_java = from_java;
 470   }
 471   bool current_pending_monitor_is_from_java() {
 472     return _current_pending_monitor_is_from_java;
 473   }
 474 
 475   // For tracking the ObjectMonitor on which this thread called Object.wait()
 476   ObjectMonitor* current_waiting_monitor() {
 477     return _current_waiting_monitor;
 478   }
 479   void set_current_waiting_monitor(ObjectMonitor* monitor) {
 480     _current_waiting_monitor = monitor;
 481   }
 482 
 483   // GC support
 484   // Apply "f->do_oop" to all root oops in "this".
 485   //   Used by JavaThread::oops_do.
 486   // Apply "cf->do_code_blob" (if !NULL) to all code blobs active in frames
 487   virtual void oops_do(OopClosure* f, CodeBlobClosure* cf);
 488 
 489   // Handles the parallel case for the method below.
 490  private:
 491   bool claim_oops_do_par_case(int collection_parity);
 492  public:
 493   // Requires that "collection_parity" is that of the current roots
 494   // iteration.  If "is_par" is false, sets the parity of "this" to
 495   // "collection_parity", and returns "true".  If "is_par" is true,
 496   // uses an atomic instruction to set the current threads parity to
 497   // "collection_parity", if it is not already.  Returns "true" iff the
 498   // calling thread does the update, this indicates that the calling thread
 499   // has claimed the thread's stack as a root groop in the current
 500   // collection.
 501   bool claim_oops_do(bool is_par, int collection_parity) {
 502     if (!is_par) {
 503       _oops_do_parity = collection_parity;
 504       return true;
 505     } else {
 506       return claim_oops_do_par_case(collection_parity);
 507     }
 508   }
 509 
 510   // jvmtiRedefineClasses support
 511   void metadata_handles_do(void f(Metadata*));
 512 
 513   // Used by fast lock support
 514   virtual bool is_lock_owned(address adr) const;
 515 
 516   // Check if address is in the stack of the thread (not just for locks).
 517   // Warning: the method can only be used on the running thread
 518   bool is_in_stack(address adr) const;
 519   // Check if address is in the usable part of the stack (excludes protected
 520   // guard pages)
 521   bool is_in_usable_stack(address adr) const;
 522 
 523   // Sets this thread as starting thread. Returns failure if thread
 524   // creation fails due to lack of memory, too many threads etc.
 525   bool set_as_starting_thread();
 526 
 527 protected:
 528   // OS data associated with the thread
 529   OSThread* _osthread;  // Platform-specific thread information
 530 
 531   // Thread local resource area for temporary allocation within the VM
 532   ResourceArea* _resource_area;
 533 
 534   DEBUG_ONLY(ResourceMark* _current_resource_mark;)
 535 
 536   // Thread local handle area for allocation of handles within the VM
 537   HandleArea* _handle_area;
 538   GrowableArray<Metadata*>* _metadata_handles;
 539 
 540   // Support for stack overflow handling, get_thread, etc.
 541   address          _stack_base;
 542   size_t           _stack_size;
 543   uintptr_t        _self_raw_id;      // used by get_thread (mutable)
 544   int              _lgrp_id;
 545 
 546  public:
 547   // Stack overflow support
 548   address stack_base() const           { assert(_stack_base != NULL,"Sanity check"); return _stack_base; }
 549   void    set_stack_base(address base) { _stack_base = base; }
 550   size_t  stack_size() const           { return _stack_size; }
 551   void    set_stack_size(size_t size)  { _stack_size = size; }
 552   address stack_end()  const           { return stack_base() - stack_size(); }
 553   void    record_stack_base_and_size();
 554 
 555   bool    on_local_stack(address adr) const {
 556     // QQQ this has knowledge of direction, ought to be a stack method
 557     return (_stack_base >= adr && adr >= stack_end());
 558   }
 559 
 560   uintptr_t self_raw_id()                    { return _self_raw_id; }
 561   void      set_self_raw_id(uintptr_t value) { _self_raw_id = value; }
 562 
 563   int     lgrp_id() const        { return _lgrp_id; }
 564   void    set_lgrp_id(int value) { _lgrp_id = value; }
 565 
 566   // Printing
 567   virtual void print_on(outputStream* st) const;
 568   void print() const { print_on(tty); }
 569   virtual void print_on_error(outputStream* st, char* buf, int buflen) const;
 570 
 571   // Debug-only code
 572 #ifdef ASSERT
 573  private:
 574   // Deadlock detection support for Mutex locks. List of locks own by thread.
 575   Monitor* _owned_locks;
 576   // Mutex::set_owner_implementation is the only place where _owned_locks is modified,
 577   // thus the friendship
 578   friend class Mutex;
 579   friend class Monitor;
 580 
 581  public:
 582   void print_owned_locks_on(outputStream* st) const;
 583   void print_owned_locks() const                 { print_owned_locks_on(tty);    }
 584   Monitor* owned_locks() const                   { return _owned_locks;          }
 585   bool owns_locks() const                        { return owned_locks() != NULL; }
 586   bool owns_locks_but_compiled_lock() const;
 587   int oops_do_parity() const                     { return _oops_do_parity; }
 588 
 589   // Deadlock detection
 590   bool allow_allocation()                        { return _allow_allocation_count == 0; }
 591   ResourceMark* current_resource_mark()          { return _current_resource_mark; }
 592   void set_current_resource_mark(ResourceMark* rm) { _current_resource_mark = rm; }
 593 #endif
 594 
 595   void check_for_valid_safepoint_state(bool potential_vm_operation) PRODUCT_RETURN;
 596 
 597  private:
 598   volatile int _jvmti_env_iteration_count;
 599 
 600  public:
 601   void entering_jvmti_env_iteration()            { ++_jvmti_env_iteration_count; }
 602   void leaving_jvmti_env_iteration()             { --_jvmti_env_iteration_count; }
 603   bool is_inside_jvmti_env_iteration()           { return _jvmti_env_iteration_count > 0; }
 604 
 605   // Code generation
 606   static ByteSize exception_file_offset()        { return byte_offset_of(Thread, _exception_file); }
 607   static ByteSize exception_line_offset()        { return byte_offset_of(Thread, _exception_line); }
 608   static ByteSize active_handles_offset()        { return byte_offset_of(Thread, _active_handles); }
 609 
 610   static ByteSize stack_base_offset()            { return byte_offset_of(Thread, _stack_base); }
 611   static ByteSize stack_size_offset()            { return byte_offset_of(Thread, _stack_size); }
 612 
 613 #define TLAB_FIELD_OFFSET(name) \
 614   static ByteSize tlab_##name##_offset()         { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::name##_offset(); }
 615 
 616   TLAB_FIELD_OFFSET(start)
 617   TLAB_FIELD_OFFSET(end)
 618   TLAB_FIELD_OFFSET(top)
 619   TLAB_FIELD_OFFSET(pf_top)
 620   TLAB_FIELD_OFFSET(size)                   // desired_size
 621   TLAB_FIELD_OFFSET(refill_waste_limit)
 622   TLAB_FIELD_OFFSET(number_of_refills)
 623   TLAB_FIELD_OFFSET(fast_refill_waste)
 624   TLAB_FIELD_OFFSET(slow_allocations)
 625 
 626 #undef TLAB_FIELD_OFFSET
 627 
 628   static ByteSize allocated_bytes_offset()       { return byte_offset_of(Thread, _allocated_bytes); }
 629 
 630  public:
 631   volatile intptr_t _Stalled;
 632   volatile int _TypeTag;
 633   ParkEvent * _ParkEvent;                     // for synchronized()
 634   ParkEvent * _SleepEvent;                    // for Thread.sleep
 635   ParkEvent * _MutexEvent;                    // for native internal Mutex/Monitor
 636   ParkEvent * _MuxEvent;                      // for low-level muxAcquire-muxRelease
 637   int NativeSyncRecursion;                    // diagnostic
 638 
 639   volatile int _OnTrap;                       // Resume-at IP delta
 640   jint _hashStateW;                           // Marsaglia Shift-XOR thread-local RNG
 641   jint _hashStateX;                           // thread-specific hashCode generator state
 642   jint _hashStateY;
 643   jint _hashStateZ;
 644   void * _schedctl;
 645 
 646 
 647   volatile jint rng[4];                      // RNG for spin loop
 648 
 649   // Low-level leaf-lock primitives used to implement synchronization
 650   // and native monitor-mutex infrastructure.
 651   // Not for general synchronization use.
 652   static void SpinAcquire(volatile int * Lock, const char * Name);
 653   static void SpinRelease(volatile int * Lock);
 654   static void muxAcquire(volatile intptr_t * Lock, const char * Name);
 655   static void muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev);
 656   static void muxRelease(volatile intptr_t * Lock);
 657 };
 658 
 659 // Inline implementation of Thread::current()
 660 inline Thread* Thread::current() {
 661   Thread* current = current_or_null();
 662   assert(current != NULL, "Thread::current() called on detached thread");
 663   return current;
 664 }
 665 
 666 inline Thread* Thread::current_or_null() {
 667 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 668   return _thr_current;
 669 #else
 670   return ThreadLocalStorage::thread();
 671 #endif
 672 }
 673 
 674 inline Thread* Thread::current_or_null_safe() {
 675   return ThreadLocalStorage::thread();
 676 }
 677 
 678 // Name support for threads.  non-JavaThread subclasses with multiple
 679 // uniquely named instances should derive from this.
 680 class NamedThread: public Thread {
 681   friend class VMStructs;
 682   enum {
 683     max_name_len = 64
 684   };
 685  private:
 686   char* _name;
 687   // log JavaThread being processed by oops_do
 688   JavaThread* _processed_thread;
 689   uint _gc_id; // The current GC id when a thread takes part in GC
 690 
 691  public:
 692   NamedThread();
 693   ~NamedThread();
 694   // May only be called once per thread.
 695   void set_name(const char* format, ...)  ATTRIBUTE_PRINTF(2, 3);
 696   void initialize_named_thread();
 697   virtual bool is_Named_thread() const { return true; }
 698   virtual char* name() const { return _name == NULL ? (char*)"Unknown Thread" : _name; }
 699   JavaThread *processed_thread() { return _processed_thread; }
 700   void set_processed_thread(JavaThread *thread) { _processed_thread = thread; }
 701   virtual void print_on(outputStream* st) const;
 702 
 703   void set_gc_id(uint gc_id) { _gc_id = gc_id; }
 704   uint gc_id() { return _gc_id; }
 705 };
 706 
 707 // Worker threads are named and have an id of an assigned work.
 708 class WorkerThread: public NamedThread {
 709  private:
 710   uint _id;
 711  public:
 712   WorkerThread() : _id(0)               { }
 713   virtual bool is_Worker_thread() const { return true; }
 714 
 715   virtual WorkerThread* as_Worker_thread() const {
 716     assert(is_Worker_thread(), "Dubious cast to WorkerThread*?");
 717     return (WorkerThread*) this;
 718   }
 719 
 720   void set_id(uint work_id)             { _id = work_id; }
 721   uint id() const                       { return _id; }
 722 };
 723 
 724 // A single WatcherThread is used for simulating timer interrupts.
 725 class WatcherThread: public Thread {
 726   friend class VMStructs;
 727  public:
 728   virtual void run();
 729 
 730  private:
 731   static WatcherThread* _watcher_thread;
 732 
 733   static bool _startable;
 734   // volatile due to at least one lock-free read
 735   volatile static bool _should_terminate;
 736 
 737   os::WatcherThreadCrashProtection* _crash_protection;
 738  public:
 739   enum SomeConstants {
 740     delay_interval = 10                          // interrupt delay in milliseconds
 741   };
 742 
 743   // Constructor
 744   WatcherThread();
 745 
 746   // No destruction allowed
 747   ~WatcherThread() {
 748     guarantee(false, "WatcherThread deletion must fix the race with VM termination");
 749   }
 750 
 751   // Tester
 752   bool is_Watcher_thread() const                 { return true; }
 753 
 754   // Printing
 755   char* name() const { return (char*)"VM Periodic Task Thread"; }
 756   void print_on(outputStream* st) const;
 757   void unpark();
 758 
 759   // Returns the single instance of WatcherThread
 760   static WatcherThread* watcher_thread()         { return _watcher_thread; }
 761 
 762   // Create and start the single instance of WatcherThread, or stop it on shutdown
 763   static void start();
 764   static void stop();
 765   // Only allow start once the VM is sufficiently initialized
 766   // Otherwise the first task to enroll will trigger the start
 767   static void make_startable();
 768 
 769   void set_crash_protection(os::WatcherThreadCrashProtection* crash_protection) {
 770     assert(Thread::current()->is_Watcher_thread(), "Can only be set by WatcherThread");
 771     _crash_protection = crash_protection;
 772   }
 773 
 774   bool has_crash_protection() const { return _crash_protection != NULL; }
 775   os::WatcherThreadCrashProtection* crash_protection() const { return _crash_protection; }
 776 
 777  private:
 778   int sleep() const;
 779 };
 780 
 781 
 782 class CompilerThread;
 783 
 784 typedef void (*ThreadFunction)(JavaThread*, TRAPS);
 785 
 786 class JavaThread: public Thread {
 787   friend class VMStructs;
 788   friend class JVMCIVMStructs;
 789   friend class WhiteBox;
 790  private:
 791   JavaThread*    _next;                          // The next thread in the Threads list
 792   oop            _threadObj;                     // The Java level thread object
 793 
 794 #ifdef ASSERT
 795  private:
 796   int _java_call_counter;
 797 
 798  public:
 799   int  java_call_counter()                       { return _java_call_counter; }
 800   void inc_java_call_counter()                   { _java_call_counter++; }
 801   void dec_java_call_counter() {
 802     assert(_java_call_counter > 0, "Invalid nesting of JavaCallWrapper");
 803     _java_call_counter--;
 804   }
 805  private:  // restore original namespace restriction
 806 #endif  // ifdef ASSERT
 807 
 808 #ifndef PRODUCT
 809  public:
 810   enum {
 811     jump_ring_buffer_size = 16
 812   };
 813  private:  // restore original namespace restriction
 814 #endif
 815 
 816   JavaFrameAnchor _anchor;                       // Encapsulation of current java frame and it state
 817 
 818   size_t _bytes_until_sample;                    // Thread local counter to determine when to sample
 819                                                  // allocations.
 820 
 821   ThreadFunction _entry_point;
 822 
 823   JNIEnv        _jni_environment;
 824 
 825   // Deopt support
 826   DeoptResourceMark*  _deopt_mark;               // Holds special ResourceMark for deoptimization
 827 
 828   intptr_t*      _must_deopt_id;                 // id of frame that needs to be deopted once we
 829                                                  // transition out of native
 830   CompiledMethod*       _deopt_nmethod;         // CompiledMethod that is currently being deoptimized
 831   vframeArray*  _vframe_array_head;              // Holds the heap of the active vframeArrays
 832   vframeArray*  _vframe_array_last;              // Holds last vFrameArray we popped
 833   // Because deoptimization is lazy we must save jvmti requests to set locals
 834   // in compiled frames until we deoptimize and we have an interpreter frame.
 835   // This holds the pointer to array (yeah like there might be more than one) of
 836   // description of compiled vframes that have locals that need to be updated.
 837   GrowableArray<jvmtiDeferredLocalVariableSet*>* _deferred_locals_updates;
 838 
 839   // Handshake value for fixing 6243940. We need a place for the i2c
 840   // adapter to store the callee Method*. This value is NEVER live
 841   // across a gc point so it does NOT have to be gc'd
 842   // The handshake is open ended since we can't be certain that it will
 843   // be NULLed. This is because we rarely ever see the race and end up
 844   // in handle_wrong_method which is the backend of the handshake. See
 845   // code in i2c adapters and handle_wrong_method.
 846 
 847   Method*       _callee_target;
 848 
 849   // Used to pass back results to the interpreter or generated code running Java code.
 850   oop           _vm_result;    // oop result is GC-preserved
 851   Metadata*     _vm_result_2;  // non-oop result
 852 
 853   // See ReduceInitialCardMarks: this holds the precise space interval of
 854   // the most recent slow path allocation for which compiled code has
 855   // elided card-marks for performance along the fast-path.
 856   MemRegion     _deferred_card_mark;
 857 
 858   MonitorChunk* _monitor_chunks;                 // Contains the off stack monitors
 859                                                  // allocated during deoptimization
 860                                                  // and by JNI_MonitorEnter/Exit
 861 
 862   // Async. requests support
 863   enum AsyncRequests {
 864     _no_async_condition = 0,
 865     _async_exception,
 866     _async_unsafe_access_error
 867   };
 868   AsyncRequests _special_runtime_exit_condition; // Enum indicating pending async. request
 869   oop           _pending_async_exception;
 870 
 871   // Safepoint support
 872  public:                                         // Expose _thread_state for SafeFetchInt()
 873   volatile JavaThreadState _thread_state;
 874  private:
 875   ThreadSafepointState *_safepoint_state;        // Holds information about a thread during a safepoint
 876   address               _saved_exception_pc;     // Saved pc of instruction where last implicit exception happened
 877 
 878   // JavaThread termination support
 879   enum TerminatedTypes {
 880     _not_terminated = 0xDEAD - 2,
 881     _thread_exiting,                             // JavaThread::exit() has been called for this thread
 882     _thread_terminated,                          // JavaThread is removed from thread list
 883     _vm_exited                                   // JavaThread is still executing native code, but VM is terminated
 884                                                  // only VM_Exit can set _vm_exited
 885   };
 886 
 887   // In general a JavaThread's _terminated field transitions as follows:
 888   //
 889   //   _not_terminated => _thread_exiting => _thread_terminated
 890   //
 891   // _vm_exited is a special value to cover the case of a JavaThread
 892   // executing native code after the VM itself is terminated.
 893   volatile TerminatedTypes _terminated;
 894   // suspend/resume support
 895   volatile bool         _suspend_equivalent;     // Suspend equivalent condition
 896   jint                  _in_deopt_handler;       // count of deoptimization
 897                                                  // handlers thread is in
 898   volatile bool         _doing_unsafe_access;    // Thread may fault due to unsafe access
 899   bool                  _do_not_unlock_if_synchronized;  // Do not unlock the receiver of a synchronized method (since it was
 900                                                          // never locked) when throwing an exception. Used by interpreter only.
 901 
 902   // JNI attach states:
 903   enum JNIAttachStates {
 904     _not_attaching_via_jni = 1,  // thread is not attaching via JNI
 905     _attaching_via_jni,          // thread is attaching via JNI
 906     _attached_via_jni            // thread has attached via JNI
 907   };
 908 
 909   // A regular JavaThread's _jni_attach_state is _not_attaching_via_jni.
 910   // A native thread that is attaching via JNI starts with a value
 911   // of _attaching_via_jni and transitions to _attached_via_jni.
 912   volatile JNIAttachStates _jni_attach_state;
 913 
 914  public:
 915   // State of the stack guard pages for this thread.
 916   enum StackGuardState {
 917     stack_guard_unused,         // not needed
 918     stack_guard_reserved_disabled,
 919     stack_guard_yellow_reserved_disabled,// disabled (temporarily) after stack overflow
 920     stack_guard_enabled         // enabled
 921   };
 922 
 923  private:
 924 
 925 #if INCLUDE_JVMCI
 926   // The _pending_* fields below are used to communicate extra information
 927   // from an uncommon trap in JVMCI compiled code to the uncommon trap handler.
 928 
 929   // Communicates the DeoptReason and DeoptAction of the uncommon trap
 930   int       _pending_deoptimization;
 931 
 932   // Specifies whether the uncommon trap is to bci 0 of a synchronized method
 933   // before the monitor has been acquired.
 934   bool      _pending_monitorenter;
 935 
 936   // Specifies if the DeoptReason for the last uncommon trap was Reason_transfer_to_interpreter
 937   bool      _pending_transfer_to_interpreter;
 938 
 939   // Guard for re-entrant call to JVMCIRuntime::adjust_comp_level
 940   bool      _adjusting_comp_level;
 941 
 942   // An object that JVMCI compiled code can use to further describe and
 943   // uniquely identify the  speculative optimization guarded by the uncommon trap
 944   oop       _pending_failed_speculation;
 945 
 946   // These fields are mutually exclusive in terms of live ranges.
 947   union {
 948     // Communicates the pc at which the most recent implicit exception occurred
 949     // from the signal handler to a deoptimization stub.
 950     address   _implicit_exception_pc;
 951 
 952     // Communicates an alternative call target to an i2c stub from a JavaCall .
 953     address   _alternate_call_target;
 954   } _jvmci;
 955 
 956   // Support for high precision, thread sensitive counters in JVMCI compiled code.
 957   jlong*    _jvmci_counters;
 958 
 959  public:
 960   static jlong* _jvmci_old_thread_counters;
 961   static void collect_counters(typeArrayOop array);
 962  private:
 963 #endif // INCLUDE_JVMCI
 964 
 965   StackGuardState  _stack_guard_state;
 966 
 967   // Precompute the limit of the stack as used in stack overflow checks.
 968   // We load it from here to simplify the stack overflow check in assembly.
 969   address          _stack_overflow_limit;
 970   address          _reserved_stack_activation;
 971 
 972   // Compiler exception handling (NOTE: The _exception_oop is *NOT* the same as _pending_exception. It is
 973   // used to temp. parsing values into and out of the runtime system during exception handling for compiled
 974   // code)
 975   volatile oop     _exception_oop;               // Exception thrown in compiled code
 976   volatile address _exception_pc;                // PC where exception happened
 977   volatile address _exception_handler_pc;        // PC for handler of exception
 978   volatile int     _is_method_handle_return;     // true (== 1) if the current exception PC is a MethodHandle call site.
 979 
 980  private:
 981   // support for JNI critical regions
 982   jint    _jni_active_critical;                  // count of entries into JNI critical region
 983 
 984   // Checked JNI: function name requires exception check
 985   char* _pending_jni_exception_check_fn;
 986 
 987   // For deadlock detection.
 988   int _depth_first_number;
 989 
 990   // JVMTI PopFrame support
 991   // This is set to popframe_pending to signal that top Java frame should be popped immediately
 992   int _popframe_condition;
 993 
 994   // If reallocation of scalar replaced objects fails, we throw OOM
 995   // and during exception propagation, pop the top
 996   // _frames_to_pop_failed_realloc frames, the ones that reference
 997   // failed reallocations.
 998   int _frames_to_pop_failed_realloc;
 999 
1000 #ifndef PRODUCT
1001   int _jmp_ring_index;
1002   struct {
1003     // We use intptr_t instead of address so debugger doesn't try and display strings
1004     intptr_t _target;
1005     intptr_t _instruction;
1006     const char*  _file;
1007     int _line;
1008   }   _jmp_ring[jump_ring_buffer_size];
1009 #endif // PRODUCT
1010 
1011 #if INCLUDE_ALL_GCS
1012   // Support for G1 barriers
1013 
1014   SATBMarkQueue _satb_mark_queue;        // Thread-local log for SATB barrier.
1015   // Set of all such queues.
1016   static SATBMarkQueueSet _satb_mark_queue_set;
1017 
1018   DirtyCardQueue _dirty_card_queue;      // Thread-local log for dirty cards.
1019   // Set of all such queues.
1020   static DirtyCardQueueSet _dirty_card_queue_set;
1021 
1022   void flush_barrier_queues();
1023 #endif // INCLUDE_ALL_GCS
1024 
1025   friend class VMThread;
1026   friend class ThreadWaitTransition;
1027   friend class VM_Exit;
1028 
1029   void initialize();                             // Initialized the instance variables
1030 
1031  public:
1032   // Constructor
1033   JavaThread(bool is_attaching_via_jni = false); // for main thread and JNI attached threads
1034   JavaThread(ThreadFunction entry_point, size_t stack_size = 0);
1035   ~JavaThread();
1036 
1037 #ifdef ASSERT
1038   // verify this JavaThread hasn't be published in the Threads::list yet
1039   void verify_not_published();
1040 #endif
1041 
1042   //JNI functiontable getter/setter for JVMTI jni function table interception API.
1043   void set_jni_functions(struct JNINativeInterface_* functionTable) {
1044     _jni_environment.functions = functionTable;
1045   }
1046   struct JNINativeInterface_* get_jni_functions() {
1047     return (struct JNINativeInterface_ *)_jni_environment.functions;
1048   }
1049 
1050   // This function is called at thread creation to allow
1051   // platform specific thread variables to be initialized.
1052   void cache_global_variables();
1053 
1054   // Executes Shutdown.shutdown()
1055   void invoke_shutdown_hooks();
1056 
1057   // Cleanup on thread exit
1058   enum ExitType {
1059     normal_exit,
1060     jni_detach
1061   };
1062   void exit(bool destroy_vm, ExitType exit_type = normal_exit);
1063 
1064   void cleanup_failed_attach_current_thread();
1065 
1066   // Testers
1067   virtual bool is_Java_thread() const            { return true;  }
1068   virtual bool can_call_java() const             { return true; }
1069 
1070   // Thread chain operations
1071   JavaThread* next() const                       { return _next; }
1072   void set_next(JavaThread* p)                   { _next = p; }
1073 
1074   // Thread oop. threadObj() can be NULL for initial JavaThread
1075   // (or for threads attached via JNI)
1076   oop threadObj() const                          { return _threadObj; }
1077   void set_threadObj(oop p)                      { _threadObj = p; }
1078 
1079   ThreadPriority java_priority() const;          // Read from threadObj()
1080 
1081   // Prepare thread and add to priority queue.  If a priority is
1082   // not specified, use the priority of the thread object. Threads_lock
1083   // must be held while this function is called.
1084   void prepare(jobject jni_thread, ThreadPriority prio=NoPriority);
1085   void prepare_ext();
1086 
1087   void set_saved_exception_pc(address pc)        { _saved_exception_pc = pc; }
1088   address saved_exception_pc()                   { return _saved_exception_pc; }
1089 
1090 
1091   ThreadFunction entry_point() const             { return _entry_point; }
1092 
1093   // Allocates a new Java level thread object for this thread. thread_name may be NULL.
1094   void allocate_threadObj(Handle thread_group, const char* thread_name, bool daemon, TRAPS);
1095 
1096   // Last frame anchor routines
1097 
1098   JavaFrameAnchor* frame_anchor(void)            { return &_anchor; }
1099 
1100   // last_Java_sp
1101   bool has_last_Java_frame() const               { return _anchor.has_last_Java_frame(); }
1102   intptr_t* last_Java_sp() const                 { return _anchor.last_Java_sp(); }
1103 
1104   // last_Java_pc
1105 
1106   address last_Java_pc(void)                     { return _anchor.last_Java_pc(); }
1107 
1108   // Bytes until next heap sample.
1109   size_t* bytes_until_sample()                   { return &_bytes_until_sample; }
1110 
1111   // Safepoint support
1112 #if !(defined(PPC64) || defined(AARCH64))
1113   JavaThreadState thread_state() const           { return _thread_state; }
1114   void set_thread_state(JavaThreadState s)       { _thread_state = s;    }
1115 #else
1116   // Use membars when accessing volatile _thread_state. See
1117   // Threads::create_vm() for size checks.
1118   inline JavaThreadState thread_state() const;
1119   inline void set_thread_state(JavaThreadState s);
1120 #endif
1121   ThreadSafepointState *safepoint_state() const  { return _safepoint_state; }
1122   void set_safepoint_state(ThreadSafepointState *state) { _safepoint_state = state; }
1123   bool is_at_poll_safepoint()                    { return _safepoint_state->is_at_poll_safepoint(); }
1124 
1125   // thread has called JavaThread::exit() or is terminated
1126   bool is_exiting()                              { return _terminated == _thread_exiting || is_terminated(); }
1127   // thread is terminated (no longer on the threads list); we compare
1128   // against the two non-terminated values so that a freed JavaThread
1129   // will also be considered terminated.
1130   bool is_terminated()                           { return _terminated != _not_terminated && _terminated != _thread_exiting; }
1131   void set_terminated(TerminatedTypes t)         { _terminated = t; }
1132   // special for Threads::remove() which is static:
1133   void set_terminated_value()                    { _terminated = _thread_terminated; }
1134   void block_if_vm_exited();
1135 
1136   bool doing_unsafe_access()                     { return _doing_unsafe_access; }
1137   void set_doing_unsafe_access(bool val)         { _doing_unsafe_access = val; }
1138 
1139   bool do_not_unlock_if_synchronized()             { return _do_not_unlock_if_synchronized; }
1140   void set_do_not_unlock_if_synchronized(bool val) { _do_not_unlock_if_synchronized = val; }
1141 
1142   // Suspend/resume support for JavaThread
1143  private:
1144   inline void set_ext_suspended();
1145   inline void clear_ext_suspended();
1146 
1147  public:
1148   void java_suspend();
1149   void java_resume();
1150   int  java_suspend_self();
1151 
1152   void check_and_wait_while_suspended() {
1153     assert(JavaThread::current() == this, "sanity check");
1154 
1155     bool do_self_suspend;
1156     do {
1157       // were we externally suspended while we were waiting?
1158       do_self_suspend = handle_special_suspend_equivalent_condition();
1159       if (do_self_suspend) {
1160         // don't surprise the thread that suspended us by returning
1161         java_suspend_self();
1162         set_suspend_equivalent();
1163       }
1164     } while (do_self_suspend);
1165   }
1166   static void check_safepoint_and_suspend_for_native_trans(JavaThread *thread);
1167   // Check for async exception in addition to safepoint and suspend request.
1168   static void check_special_condition_for_native_trans(JavaThread *thread);
1169 
1170   // Same as check_special_condition_for_native_trans but finishes the
1171   // transition into thread_in_Java mode so that it can potentially
1172   // block.
1173   static void check_special_condition_for_native_trans_and_transition(JavaThread *thread);
1174 
1175   bool is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits);
1176   bool is_ext_suspend_completed_with_lock(uint32_t *bits) {
1177     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1178     // Warning: is_ext_suspend_completed() may temporarily drop the
1179     // SR_lock to allow the thread to reach a stable thread state if
1180     // it is currently in a transient thread state.
1181     return is_ext_suspend_completed(false /* !called_by_wait */,
1182                                     SuspendRetryDelay, bits);
1183   }
1184 
1185   // We cannot allow wait_for_ext_suspend_completion() to run forever or
1186   // we could hang. SuspendRetryCount and SuspendRetryDelay are normally
1187   // passed as the count and delay parameters. Experiments with specific
1188   // calls to wait_for_ext_suspend_completion() can be done by passing
1189   // other values in the code. Experiments with all calls can be done
1190   // via the appropriate -XX options.
1191   bool wait_for_ext_suspend_completion(int count, int delay, uint32_t *bits);
1192 
1193   inline void set_external_suspend();
1194   inline void clear_external_suspend();
1195 
1196   inline void set_deopt_suspend();
1197   inline void clear_deopt_suspend();
1198   bool is_deopt_suspend()         { return (_suspend_flags & _deopt_suspend) != 0; }
1199 
1200   bool is_external_suspend() const {
1201     return (_suspend_flags & _external_suspend) != 0;
1202   }
1203   // Whenever a thread transitions from native to vm/java it must suspend
1204   // if external|deopt suspend is present.
1205   bool is_suspend_after_native() const {
1206     return (_suspend_flags & (_external_suspend | _deopt_suspend)) != 0;
1207   }
1208 
1209   // external suspend request is completed
1210   bool is_ext_suspended() const {
1211     return (_suspend_flags & _ext_suspended) != 0;
1212   }
1213 
1214   bool is_external_suspend_with_lock() const {
1215     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1216     return is_external_suspend();
1217   }
1218 
1219   // Special method to handle a pending external suspend request
1220   // when a suspend equivalent condition lifts.
1221   bool handle_special_suspend_equivalent_condition() {
1222     assert(is_suspend_equivalent(),
1223            "should only be called in a suspend equivalence condition");
1224     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1225     bool ret = is_external_suspend();
1226     if (!ret) {
1227       // not about to self-suspend so clear suspend equivalence
1228       clear_suspend_equivalent();
1229     }
1230     // implied else:
1231     // We have a pending external suspend request so we leave the
1232     // suspend_equivalent flag set until java_suspend_self() sets
1233     // the ext_suspended flag and clears the suspend_equivalent
1234     // flag. This insures that wait_for_ext_suspend_completion()
1235     // will return consistent values.
1236     return ret;
1237   }
1238 
1239   // utility methods to see if we are doing some kind of suspension
1240   bool is_being_ext_suspended() const            {
1241     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1242     return is_ext_suspended() || is_external_suspend();
1243   }
1244 
1245   bool is_suspend_equivalent() const             { return _suspend_equivalent; }
1246 
1247   void set_suspend_equivalent()                  { _suspend_equivalent = true; }
1248   void clear_suspend_equivalent()                { _suspend_equivalent = false; }
1249 
1250   // Thread.stop support
1251   void send_thread_stop(oop throwable);
1252   AsyncRequests clear_special_runtime_exit_condition() {
1253     AsyncRequests x = _special_runtime_exit_condition;
1254     _special_runtime_exit_condition = _no_async_condition;
1255     return x;
1256   }
1257 
1258   // Are any async conditions present?
1259   bool has_async_condition() { return (_special_runtime_exit_condition != _no_async_condition); }
1260 
1261   void check_and_handle_async_exceptions(bool check_unsafe_error = true);
1262 
1263   // these next two are also used for self-suspension and async exception support
1264   void handle_special_runtime_exit_condition(bool check_asyncs = true);
1265 
1266   // Return true if JavaThread has an asynchronous condition or
1267   // if external suspension is requested.
1268   bool has_special_runtime_exit_condition() {
1269     // We call is_external_suspend() last since external suspend should
1270     // be less common. Because we don't use is_external_suspend_with_lock
1271     // it is possible that we won't see an asynchronous external suspend
1272     // request that has just gotten started, i.e., SR_lock grabbed but
1273     // _external_suspend field change either not made yet or not visible
1274     // yet. However, this is okay because the request is asynchronous and
1275     // we will see the new flag value the next time through. It's also
1276     // possible that the external suspend request is dropped after
1277     // we have checked is_external_suspend(), we will recheck its value
1278     // under SR_lock in java_suspend_self().
1279     return (_special_runtime_exit_condition != _no_async_condition) ||
1280             is_external_suspend() || is_deopt_suspend();
1281   }
1282 
1283   void set_pending_unsafe_access_error()          { _special_runtime_exit_condition = _async_unsafe_access_error; }
1284 
1285   inline void set_pending_async_exception(oop e);
1286 
1287   // Fast-locking support
1288   bool is_lock_owned(address adr) const;
1289 
1290   // Accessors for vframe array top
1291   // The linked list of vframe arrays are sorted on sp. This means when we
1292   // unpack the head must contain the vframe array to unpack.
1293   void set_vframe_array_head(vframeArray* value) { _vframe_array_head = value; }
1294   vframeArray* vframe_array_head() const         { return _vframe_array_head;  }
1295 
1296   // Side structure for deferring update of java frame locals until deopt occurs
1297   GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred_locals() const { return _deferred_locals_updates; }
1298   void set_deferred_locals(GrowableArray<jvmtiDeferredLocalVariableSet *>* vf) { _deferred_locals_updates = vf; }
1299 
1300   // These only really exist to make debugging deopt problems simpler
1301 
1302   void set_vframe_array_last(vframeArray* value) { _vframe_array_last = value; }
1303   vframeArray* vframe_array_last() const         { return _vframe_array_last;  }
1304 
1305   // The special resourceMark used during deoptimization
1306 
1307   void set_deopt_mark(DeoptResourceMark* value)  { _deopt_mark = value; }
1308   DeoptResourceMark* deopt_mark(void)            { return _deopt_mark; }
1309 
1310   intptr_t* must_deopt_id()                      { return _must_deopt_id; }
1311   void     set_must_deopt_id(intptr_t* id)       { _must_deopt_id = id; }
1312   void     clear_must_deopt_id()                 { _must_deopt_id = NULL; }
1313 
1314   void set_deopt_compiled_method(CompiledMethod* nm)  { _deopt_nmethod = nm; }
1315   CompiledMethod* deopt_compiled_method()        { return _deopt_nmethod; }
1316 
1317   Method*    callee_target() const               { return _callee_target; }
1318   void set_callee_target  (Method* x)          { _callee_target   = x; }
1319 
1320   // Oop results of vm runtime calls
1321   oop  vm_result() const                         { return _vm_result; }
1322   void set_vm_result  (oop x)                    { _vm_result   = x; }
1323 
1324   Metadata*    vm_result_2() const               { return _vm_result_2; }
1325   void set_vm_result_2  (Metadata* x)          { _vm_result_2   = x; }
1326 
1327   MemRegion deferred_card_mark() const           { return _deferred_card_mark; }
1328   void set_deferred_card_mark(MemRegion mr)      { _deferred_card_mark = mr;   }
1329 
1330 #if INCLUDE_JVMCI
1331   int  pending_deoptimization() const             { return _pending_deoptimization; }
1332   oop  pending_failed_speculation() const         { return _pending_failed_speculation; }
1333   bool adjusting_comp_level() const               { return _adjusting_comp_level; }
1334   void set_adjusting_comp_level(bool b)           { _adjusting_comp_level = b; }
1335   bool has_pending_monitorenter() const           { return _pending_monitorenter; }
1336   void set_pending_monitorenter(bool b)           { _pending_monitorenter = b; }
1337   void set_pending_deoptimization(int reason)     { _pending_deoptimization = reason; }
1338   void set_pending_failed_speculation(oop failed_speculation) { _pending_failed_speculation = failed_speculation; }
1339   void set_pending_transfer_to_interpreter(bool b) { _pending_transfer_to_interpreter = b; }
1340   void set_jvmci_alternate_call_target(address a) { assert(_jvmci._alternate_call_target == NULL, "must be"); _jvmci._alternate_call_target = a; }
1341   void set_jvmci_implicit_exception_pc(address a) { assert(_jvmci._implicit_exception_pc == NULL, "must be"); _jvmci._implicit_exception_pc = a; }
1342 #endif // INCLUDE_JVMCI
1343 
1344   // Exception handling for compiled methods
1345   oop      exception_oop() const                 { return _exception_oop; }
1346   address  exception_pc() const                  { return _exception_pc; }
1347   address  exception_handler_pc() const          { return _exception_handler_pc; }
1348   bool     is_method_handle_return() const       { return _is_method_handle_return == 1; }
1349 
1350   void set_exception_oop(oop o)                  { (void)const_cast<oop&>(_exception_oop = o); }
1351   void set_exception_pc(address a)               { _exception_pc = a; }
1352   void set_exception_handler_pc(address a)       { _exception_handler_pc = a; }
1353   void set_is_method_handle_return(bool value)   { _is_method_handle_return = value ? 1 : 0; }
1354 
1355   void clear_exception_oop_and_pc() {
1356     set_exception_oop(NULL);
1357     set_exception_pc(NULL);
1358   }
1359 
1360   // Stack overflow support
1361   //
1362   //  (small addresses)
1363   //
1364   //  --  <-- stack_end()                   ---
1365   //  |                                      |
1366   //  |  red pages                           |
1367   //  |                                      |
1368   //  --  <-- stack_red_zone_base()          |
1369   //  |                                      |
1370   //  |                                     guard
1371   //  |  yellow pages                       zone
1372   //  |                                      |
1373   //  |                                      |
1374   //  --  <-- stack_yellow_zone_base()       |
1375   //  |                                      |
1376   //  |                                      |
1377   //  |  reserved pages                      |
1378   //  |                                      |
1379   //  --  <-- stack_reserved_zone_base()    ---      ---
1380   //                                                 /|\  shadow     <--  stack_overflow_limit() (somewhere in here)
1381   //                                                  |   zone
1382   //                                                 \|/  size
1383   //  some untouched memory                          ---
1384   //
1385   //
1386   //  --
1387   //  |
1388   //  |  shadow zone
1389   //  |
1390   //  --
1391   //  x    frame n
1392   //  --
1393   //  x    frame n-1
1394   //  x
1395   //  --
1396   //  ...
1397   //
1398   //  --
1399   //  x    frame 0
1400   //  --  <-- stack_base()
1401   //
1402   //  (large addresses)
1403   //
1404 
1405  private:
1406   // These values are derived from flags StackRedPages, StackYellowPages,
1407   // StackReservedPages and StackShadowPages. The zone size is determined
1408   // ergonomically if page_size > 4K.
1409   static size_t _stack_red_zone_size;
1410   static size_t _stack_yellow_zone_size;
1411   static size_t _stack_reserved_zone_size;
1412   static size_t _stack_shadow_zone_size;
1413  public:
1414   inline size_t stack_available(address cur_sp);
1415 
1416   static size_t stack_red_zone_size() {
1417     assert(_stack_red_zone_size > 0, "Don't call this before the field is initialized.");
1418     return _stack_red_zone_size;
1419   }
1420   static void set_stack_red_zone_size(size_t s) {
1421     assert(is_size_aligned(s, os::vm_page_size()),
1422            "We can not protect if the red zone size is not page aligned.");
1423     assert(_stack_red_zone_size == 0, "This should be called only once.");
1424     _stack_red_zone_size = s;
1425   }
1426   address stack_red_zone_base() {
1427     return (address)(stack_end() + stack_red_zone_size());
1428   }
1429   bool in_stack_red_zone(address a) {
1430     return a <= stack_red_zone_base() && a >= stack_end();
1431   }
1432 
1433   static size_t stack_yellow_zone_size() {
1434     assert(_stack_yellow_zone_size > 0, "Don't call this before the field is initialized.");
1435     return _stack_yellow_zone_size;
1436   }
1437   static void set_stack_yellow_zone_size(size_t s) {
1438     assert(is_size_aligned(s, os::vm_page_size()),
1439            "We can not protect if the yellow zone size is not page aligned.");
1440     assert(_stack_yellow_zone_size == 0, "This should be called only once.");
1441     _stack_yellow_zone_size = s;
1442   }
1443 
1444   static size_t stack_reserved_zone_size() {
1445     // _stack_reserved_zone_size may be 0. This indicates the feature is off.
1446     return _stack_reserved_zone_size;
1447   }
1448   static void set_stack_reserved_zone_size(size_t s) {
1449     assert(is_size_aligned(s, os::vm_page_size()),
1450            "We can not protect if the reserved zone size is not page aligned.");
1451     assert(_stack_reserved_zone_size == 0, "This should be called only once.");
1452     _stack_reserved_zone_size = s;
1453   }
1454   address stack_reserved_zone_base() {
1455     return (address)(stack_end() +
1456                      (stack_red_zone_size() + stack_yellow_zone_size() + stack_reserved_zone_size()));
1457   }
1458   bool in_stack_reserved_zone(address a) {
1459     return (a <= stack_reserved_zone_base()) &&
1460            (a >= (address)((intptr_t)stack_reserved_zone_base() - stack_reserved_zone_size()));
1461   }
1462 
1463   static size_t stack_yellow_reserved_zone_size() {
1464     return _stack_yellow_zone_size + _stack_reserved_zone_size;
1465   }
1466   bool in_stack_yellow_reserved_zone(address a) {
1467     return (a <= stack_reserved_zone_base()) && (a >= stack_red_zone_base());
1468   }
1469 
1470   // Size of red + yellow + reserved zones.
1471   static size_t stack_guard_zone_size() {
1472     return stack_red_zone_size() + stack_yellow_reserved_zone_size();
1473   }
1474 
1475   static size_t stack_shadow_zone_size() {
1476     assert(_stack_shadow_zone_size > 0, "Don't call this before the field is initialized.");
1477     return _stack_shadow_zone_size;
1478   }
1479   static void set_stack_shadow_zone_size(size_t s) {
1480     // The shadow area is not allocated or protected, so
1481     // it needs not be page aligned.
1482     // But the stack bang currently assumes that it is a
1483     // multiple of page size. This guarantees that the bang
1484     // loop touches all pages in the shadow zone.
1485     // This can be guaranteed differently, as well.  E.g., if
1486     // the page size is a multiple of 4K, banging in 4K steps
1487     // suffices to touch all pages. (Some pages are banged
1488     // several times, though.)
1489     assert(is_size_aligned(s, os::vm_page_size()),
1490            "Stack bang assumes multiple of page size.");
1491     assert(_stack_shadow_zone_size == 0, "This should be called only once.");
1492     _stack_shadow_zone_size = s;
1493   }
1494 
1495   void create_stack_guard_pages();
1496   void remove_stack_guard_pages();
1497 
1498   void enable_stack_reserved_zone();
1499   void disable_stack_reserved_zone();
1500   void enable_stack_yellow_reserved_zone();
1501   void disable_stack_yellow_reserved_zone();
1502   void enable_stack_red_zone();
1503   void disable_stack_red_zone();
1504 
1505   inline bool stack_guard_zone_unused();
1506   inline bool stack_yellow_reserved_zone_disabled();
1507   inline bool stack_reserved_zone_disabled();
1508   inline bool stack_guards_enabled();
1509 
1510   address reserved_stack_activation() const { return _reserved_stack_activation; }
1511   void set_reserved_stack_activation(address addr) {
1512     assert(_reserved_stack_activation == stack_base()
1513             || _reserved_stack_activation == NULL
1514             || addr == stack_base(), "Must not be set twice");
1515     _reserved_stack_activation = addr;
1516   }
1517 
1518   // Attempt to reguard the stack after a stack overflow may have occurred.
1519   // Returns true if (a) guard pages are not needed on this thread, (b) the
1520   // pages are already guarded, or (c) the pages were successfully reguarded.
1521   // Returns false if there is not enough stack space to reguard the pages, in
1522   // which case the caller should unwind a frame and try again.  The argument
1523   // should be the caller's (approximate) sp.
1524   bool reguard_stack(address cur_sp);
1525   // Similar to above but see if current stackpoint is out of the guard area
1526   // and reguard if possible.
1527   bool reguard_stack(void);
1528 
1529   address stack_overflow_limit() { return _stack_overflow_limit; }
1530   void set_stack_overflow_limit() {
1531     _stack_overflow_limit =
1532       stack_end() + MAX2(JavaThread::stack_guard_zone_size(), JavaThread::stack_shadow_zone_size());
1533   }
1534 
1535   // Misc. accessors/mutators
1536   void set_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = true; }
1537   void clr_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = false; }
1538   bool do_not_unlock(void)                       { return _do_not_unlock_if_synchronized; }
1539 
1540 #ifndef PRODUCT
1541   void record_jump(address target, address instr, const char* file, int line);
1542 #endif // PRODUCT
1543 
1544   // For assembly stub generation
1545   static ByteSize threadObj_offset()             { return byte_offset_of(JavaThread, _threadObj); }
1546 #ifndef PRODUCT
1547   static ByteSize jmp_ring_index_offset()        { return byte_offset_of(JavaThread, _jmp_ring_index); }
1548   static ByteSize jmp_ring_offset()              { return byte_offset_of(JavaThread, _jmp_ring); }
1549 #endif // PRODUCT
1550   static ByteSize jni_environment_offset()       { return byte_offset_of(JavaThread, _jni_environment); }
1551   static ByteSize pending_jni_exception_check_fn_offset() {
1552     return byte_offset_of(JavaThread, _pending_jni_exception_check_fn);
1553   }
1554   static ByteSize last_Java_sp_offset() {
1555     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset();
1556   }
1557   static ByteSize last_Java_pc_offset() {
1558     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset();
1559   }
1560   static ByteSize frame_anchor_offset() {
1561     return byte_offset_of(JavaThread, _anchor);
1562   }
1563   static ByteSize bytes_until_sample_offset()    { return byte_offset_of(JavaThread, _bytes_until_sample); }
1564   static ByteSize callee_target_offset()         { return byte_offset_of(JavaThread, _callee_target); }
1565   static ByteSize vm_result_offset()             { return byte_offset_of(JavaThread, _vm_result); }
1566   static ByteSize vm_result_2_offset()           { return byte_offset_of(JavaThread, _vm_result_2); }
1567   static ByteSize thread_state_offset()          { return byte_offset_of(JavaThread, _thread_state); }
1568   static ByteSize saved_exception_pc_offset()    { return byte_offset_of(JavaThread, _saved_exception_pc); }
1569   static ByteSize osthread_offset()              { return byte_offset_of(JavaThread, _osthread); }
1570 #if INCLUDE_JVMCI
1571   static ByteSize pending_deoptimization_offset() { return byte_offset_of(JavaThread, _pending_deoptimization); }
1572   static ByteSize pending_monitorenter_offset()  { return byte_offset_of(JavaThread, _pending_monitorenter); }
1573   static ByteSize pending_failed_speculation_offset() { return byte_offset_of(JavaThread, _pending_failed_speculation); }
1574   static ByteSize jvmci_alternate_call_target_offset() { return byte_offset_of(JavaThread, _jvmci._alternate_call_target); }
1575   static ByteSize jvmci_implicit_exception_pc_offset() { return byte_offset_of(JavaThread, _jvmci._implicit_exception_pc); }
1576   static ByteSize jvmci_counters_offset()        { return byte_offset_of(JavaThread, _jvmci_counters); }
1577 #endif // INCLUDE_JVMCI
1578   static ByteSize exception_oop_offset()         { return byte_offset_of(JavaThread, _exception_oop); }
1579   static ByteSize exception_pc_offset()          { return byte_offset_of(JavaThread, _exception_pc); }
1580   static ByteSize exception_handler_pc_offset()  { return byte_offset_of(JavaThread, _exception_handler_pc); }
1581   static ByteSize stack_overflow_limit_offset()  { return byte_offset_of(JavaThread, _stack_overflow_limit); }
1582   static ByteSize is_method_handle_return_offset() { return byte_offset_of(JavaThread, _is_method_handle_return); }
1583   static ByteSize stack_guard_state_offset()     { return byte_offset_of(JavaThread, _stack_guard_state); }
1584   static ByteSize reserved_stack_activation_offset() { return byte_offset_of(JavaThread, _reserved_stack_activation); }
1585   static ByteSize suspend_flags_offset()         { return byte_offset_of(JavaThread, _suspend_flags); }
1586 
1587   static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
1588   static ByteSize should_post_on_exceptions_flag_offset() {
1589     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
1590   }
1591 
1592 #if INCLUDE_ALL_GCS
1593   static ByteSize satb_mark_queue_offset()       { return byte_offset_of(JavaThread, _satb_mark_queue); }
1594   static ByteSize dirty_card_queue_offset()      { return byte_offset_of(JavaThread, _dirty_card_queue); }
1595 #endif // INCLUDE_ALL_GCS
1596 
1597   // Returns the jni environment for this thread
1598   JNIEnv* jni_environment()                      { return &_jni_environment; }
1599 
1600   static JavaThread* thread_from_jni_environment(JNIEnv* env) {
1601     JavaThread *thread_from_jni_env = (JavaThread*)((intptr_t)env - in_bytes(jni_environment_offset()));
1602     // Only return NULL if thread is off the thread list; starting to
1603     // exit should not return NULL.
1604     if (thread_from_jni_env->is_terminated()) {
1605       thread_from_jni_env->block_if_vm_exited();
1606       return NULL;
1607     } else {
1608       return thread_from_jni_env;
1609     }
1610   }
1611 
1612   // JNI critical regions. These can nest.
1613   bool in_critical()    { return _jni_active_critical > 0; }
1614   bool in_last_critical()  { return _jni_active_critical == 1; }
1615   void enter_critical() {
1616     assert(Thread::current() == this ||
1617            (Thread::current()->is_VM_thread() &&
1618            SafepointSynchronize::is_synchronizing()),
1619            "this must be current thread or synchronizing");
1620     _jni_active_critical++;
1621   }
1622   void exit_critical() {
1623     assert(Thread::current() == this, "this must be current thread");
1624     _jni_active_critical--;
1625     assert(_jni_active_critical >= 0, "JNI critical nesting problem?");
1626   }
1627 
1628   // Checked JNI: is the programmer required to check for exceptions, if so specify
1629   // which function name. Returning to a Java frame should implicitly clear the
1630   // pending check, this is done for Native->Java transitions (i.e. user JNI code).
1631   // VM->Java transistions are not cleared, it is expected that JNI code enclosed
1632   // within ThreadToNativeFromVM makes proper exception checks (i.e. VM internal).
1633   bool is_pending_jni_exception_check() const { return _pending_jni_exception_check_fn != NULL; }
1634   void clear_pending_jni_exception_check() { _pending_jni_exception_check_fn = NULL; }
1635   const char* get_pending_jni_exception_check() const { return _pending_jni_exception_check_fn; }
1636   void set_pending_jni_exception_check(const char* fn_name) { _pending_jni_exception_check_fn = (char*) fn_name; }
1637 
1638   // For deadlock detection
1639   int depth_first_number() { return _depth_first_number; }
1640   void set_depth_first_number(int dfn) { _depth_first_number = dfn; }
1641 
1642  private:
1643   void set_monitor_chunks(MonitorChunk* monitor_chunks) { _monitor_chunks = monitor_chunks; }
1644 
1645  public:
1646   MonitorChunk* monitor_chunks() const           { return _monitor_chunks; }
1647   void add_monitor_chunk(MonitorChunk* chunk);
1648   void remove_monitor_chunk(MonitorChunk* chunk);
1649   bool in_deopt_handler() const                  { return _in_deopt_handler > 0; }
1650   void inc_in_deopt_handler()                    { _in_deopt_handler++; }
1651   void dec_in_deopt_handler() {
1652     assert(_in_deopt_handler > 0, "mismatched deopt nesting");
1653     if (_in_deopt_handler > 0) { // robustness
1654       _in_deopt_handler--;
1655     }
1656   }
1657 
1658  private:
1659   void set_entry_point(ThreadFunction entry_point) { _entry_point = entry_point; }
1660 
1661  public:
1662 
1663   // Frame iteration; calls the function f for all frames on the stack
1664   void frames_do(void f(frame*, const RegisterMap*));
1665 
1666   // Memory operations
1667   void oops_do(OopClosure* f, CodeBlobClosure* cf);
1668 
1669   // Sweeper operations
1670   virtual void nmethods_do(CodeBlobClosure* cf);
1671 
1672   // RedefineClasses Support
1673   void metadata_do(void f(Metadata*));
1674 
1675   // Misc. operations
1676   char* name() const { return (char*)get_thread_name(); }
1677   void print_on(outputStream* st) const;
1678   void print_value();
1679   void print_thread_state_on(outputStream*) const      PRODUCT_RETURN;
1680   void print_thread_state() const                      PRODUCT_RETURN;
1681   void print_on_error(outputStream* st, char* buf, int buflen) const;
1682   void print_name_on_error(outputStream* st, char* buf, int buflen) const;
1683   void verify();
1684   const char* get_thread_name() const;
1685  private:
1686   // factor out low-level mechanics for use in both normal and error cases
1687   const char* get_thread_name_string(char* buf = NULL, int buflen = 0) const;
1688  public:
1689   const char* get_threadgroup_name() const;
1690   const char* get_parent_name() const;
1691 
1692   // Accessing frames
1693   frame last_frame() {
1694     _anchor.make_walkable(this);
1695     return pd_last_frame();
1696   }
1697   javaVFrame* last_java_vframe(RegisterMap* reg_map);
1698 
1699   // Returns method at 'depth' java or native frames down the stack
1700   // Used for security checks
1701   Klass* security_get_caller_class(int depth);
1702 
1703   // Print stack trace in external format
1704   void print_stack_on(outputStream* st);
1705   void print_stack() { print_stack_on(tty); }
1706 
1707   // Print stack traces in various internal formats
1708   void trace_stack()                             PRODUCT_RETURN;
1709   void trace_stack_from(vframe* start_vf)        PRODUCT_RETURN;
1710   void trace_frames()                            PRODUCT_RETURN;
1711   void trace_oops()                              PRODUCT_RETURN;
1712 
1713   // Print an annotated view of the stack frames
1714   void print_frame_layout(int depth = 0, bool validate_only = false) NOT_DEBUG_RETURN;
1715   void validate_frame_layout() {
1716     print_frame_layout(0, true);
1717   }
1718 
1719   // Returns the number of stack frames on the stack
1720   int depth() const;
1721 
1722   // Function for testing deoptimization
1723   void deoptimize();
1724   void make_zombies();
1725 
1726   void deoptimized_wrt_marked_nmethods();
1727 
1728   // Profiling operation (see fprofile.cpp)
1729  public:
1730   bool profile_last_Java_frame(frame* fr);
1731 
1732  private:
1733   ThreadProfiler* _thread_profiler;
1734  private:
1735   friend class FlatProfiler;                    // uses both [gs]et_thread_profiler.
1736   friend class FlatProfilerTask;                // uses get_thread_profiler.
1737   friend class ThreadProfilerMark;              // uses get_thread_profiler.
1738   ThreadProfiler* get_thread_profiler()         { return _thread_profiler; }
1739   ThreadProfiler* set_thread_profiler(ThreadProfiler* tp) {
1740     ThreadProfiler* result = _thread_profiler;
1741     _thread_profiler = tp;
1742     return result;
1743   }
1744 
1745  public:
1746   // Returns the running thread as a JavaThread
1747   static inline JavaThread* current();
1748 
1749   // Returns the active Java thread.  Do not use this if you know you are calling
1750   // from a JavaThread, as it's slower than JavaThread::current.  If called from
1751   // the VMThread, it also returns the JavaThread that instigated the VMThread's
1752   // operation.  You may not want that either.
1753   static JavaThread* active();
1754 
1755   inline CompilerThread* as_CompilerThread();
1756 
1757  public:
1758   virtual void run();
1759   void thread_main_inner();
1760 
1761  private:
1762   // PRIVILEGED STACK
1763   PrivilegedElement*  _privileged_stack_top;
1764   GrowableArray<oop>* _array_for_gc;
1765  public:
1766 
1767   // Returns the privileged_stack information.
1768   PrivilegedElement* privileged_stack_top() const       { return _privileged_stack_top; }
1769   void set_privileged_stack_top(PrivilegedElement *e)   { _privileged_stack_top = e; }
1770   void register_array_for_gc(GrowableArray<oop>* array) { _array_for_gc = array; }
1771 
1772  public:
1773   // Thread local information maintained by JVMTI.
1774   void set_jvmti_thread_state(JvmtiThreadState *value)                           { _jvmti_thread_state = value; }
1775   // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
1776   // getter is used to get this JavaThread's JvmtiThreadState if it has
1777   // one which means NULL can be returned. JvmtiThreadState::state_for()
1778   // is used to get the specified JavaThread's JvmtiThreadState if it has
1779   // one or it allocates a new JvmtiThreadState for the JavaThread and
1780   // returns it. JvmtiThreadState::state_for() will return NULL only if
1781   // the specified JavaThread is exiting.
1782   JvmtiThreadState *jvmti_thread_state() const                                   { return _jvmti_thread_state; }
1783   static ByteSize jvmti_thread_state_offset()                                    { return byte_offset_of(JavaThread, _jvmti_thread_state); }
1784   void set_jvmti_get_loaded_classes_closure(JvmtiGetLoadedClassesClosure* value) { _jvmti_get_loaded_classes_closure = value; }
1785   JvmtiGetLoadedClassesClosure* get_jvmti_get_loaded_classes_closure() const     { return _jvmti_get_loaded_classes_closure; }
1786 
1787   // JVMTI PopFrame support
1788   // Setting and clearing popframe_condition
1789   // All of these enumerated values are bits. popframe_pending
1790   // indicates that a PopFrame() has been requested and not yet been
1791   // completed. popframe_processing indicates that that PopFrame() is in
1792   // the process of being completed. popframe_force_deopt_reexecution_bit
1793   // indicates that special handling is required when returning to a
1794   // deoptimized caller.
1795   enum PopCondition {
1796     popframe_inactive                      = 0x00,
1797     popframe_pending_bit                   = 0x01,
1798     popframe_processing_bit                = 0x02,
1799     popframe_force_deopt_reexecution_bit   = 0x04
1800   };
1801   PopCondition popframe_condition()                   { return (PopCondition) _popframe_condition; }
1802   void set_popframe_condition(PopCondition c)         { _popframe_condition = c; }
1803   void set_popframe_condition_bit(PopCondition c)     { _popframe_condition |= c; }
1804   void clear_popframe_condition()                     { _popframe_condition = popframe_inactive; }
1805   static ByteSize popframe_condition_offset()         { return byte_offset_of(JavaThread, _popframe_condition); }
1806   bool has_pending_popframe()                         { return (popframe_condition() & popframe_pending_bit) != 0; }
1807   bool popframe_forcing_deopt_reexecution()           { return (popframe_condition() & popframe_force_deopt_reexecution_bit) != 0; }
1808   void clear_popframe_forcing_deopt_reexecution()     { _popframe_condition &= ~popframe_force_deopt_reexecution_bit; }
1809 #ifdef CC_INTERP
1810   bool pop_frame_pending(void)                        { return ((_popframe_condition & popframe_pending_bit) != 0); }
1811   void clr_pop_frame_pending(void)                    { _popframe_condition = popframe_inactive; }
1812   bool pop_frame_in_process(void)                     { return ((_popframe_condition & popframe_processing_bit) != 0); }
1813   void set_pop_frame_in_process(void)                 { _popframe_condition |= popframe_processing_bit; }
1814   void clr_pop_frame_in_process(void)                 { _popframe_condition &= ~popframe_processing_bit; }
1815 #endif
1816 
1817   int frames_to_pop_failed_realloc() const            { return _frames_to_pop_failed_realloc; }
1818   void set_frames_to_pop_failed_realloc(int nb)       { _frames_to_pop_failed_realloc = nb; }
1819   void dec_frames_to_pop_failed_realloc()             { _frames_to_pop_failed_realloc--; }
1820 
1821  private:
1822   // Saved incoming arguments to popped frame.
1823   // Used only when popped interpreted frame returns to deoptimized frame.
1824   void*    _popframe_preserved_args;
1825   int      _popframe_preserved_args_size;
1826 
1827  public:
1828   void  popframe_preserve_args(ByteSize size_in_bytes, void* start);
1829   void* popframe_preserved_args();
1830   ByteSize popframe_preserved_args_size();
1831   WordSize popframe_preserved_args_size_in_words();
1832   void  popframe_free_preserved_args();
1833 
1834 
1835  private:
1836   JvmtiThreadState *_jvmti_thread_state;
1837   JvmtiGetLoadedClassesClosure* _jvmti_get_loaded_classes_closure;
1838 
1839   // Used by the interpreter in fullspeed mode for frame pop, method
1840   // entry, method exit and single stepping support. This field is
1841   // only set to non-zero by the VM_EnterInterpOnlyMode VM operation.
1842   // It can be set to zero asynchronously (i.e., without a VM operation
1843   // or a lock) so we have to be very careful.
1844   int               _interp_only_mode;
1845 
1846  public:
1847   // used by the interpreter for fullspeed debugging support (see above)
1848   static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); }
1849   bool is_interp_only_mode()                { return (_interp_only_mode != 0); }
1850   int get_interp_only_mode()                { return _interp_only_mode; }
1851   void increment_interp_only_mode()         { ++_interp_only_mode; }
1852   void decrement_interp_only_mode()         { --_interp_only_mode; }
1853 
1854   // support for cached flag that indicates whether exceptions need to be posted for this thread
1855   // if this is false, we can avoid deoptimizing when events are thrown
1856   // this gets set to reflect whether jvmtiExport::post_exception_throw would actually do anything
1857  private:
1858   int    _should_post_on_exceptions_flag;
1859 
1860  public:
1861   int   should_post_on_exceptions_flag()  { return _should_post_on_exceptions_flag; }
1862   void  set_should_post_on_exceptions_flag(int val)  { _should_post_on_exceptions_flag = val; }
1863 
1864  private:
1865   ThreadStatistics *_thread_stat;
1866 
1867  public:
1868   ThreadStatistics* get_thread_stat() const    { return _thread_stat; }
1869 
1870   // Return a blocker object for which this thread is blocked parking.
1871   oop current_park_blocker();
1872 
1873  private:
1874   static size_t _stack_size_at_create;
1875 
1876  public:
1877   static inline size_t stack_size_at_create(void) {
1878     return _stack_size_at_create;
1879   }
1880   static inline void set_stack_size_at_create(size_t value) {
1881     _stack_size_at_create = value;
1882   }
1883 
1884 #if INCLUDE_ALL_GCS
1885   // SATB marking queue support
1886   SATBMarkQueue& satb_mark_queue() { return _satb_mark_queue; }
1887   static SATBMarkQueueSet& satb_mark_queue_set() {
1888     return _satb_mark_queue_set;
1889   }
1890 
1891   // Dirty card queue support
1892   DirtyCardQueue& dirty_card_queue() { return _dirty_card_queue; }
1893   static DirtyCardQueueSet& dirty_card_queue_set() {
1894     return _dirty_card_queue_set;
1895   }
1896 #endif // INCLUDE_ALL_GCS
1897 
1898   // This method initializes the SATB and dirty card queues before a
1899   // JavaThread is added to the Java thread list. Right now, we don't
1900   // have to do anything to the dirty card queue (it should have been
1901   // activated when the thread was created), but we have to activate
1902   // the SATB queue if the thread is created while a marking cycle is
1903   // in progress. The activation / de-activation of the SATB queues at
1904   // the beginning / end of a marking cycle is done during safepoints
1905   // so we have to make sure this method is called outside one to be
1906   // able to safely read the active field of the SATB queue set. Right
1907   // now, it is called just before the thread is added to the Java
1908   // thread list in the Threads::add() method. That method is holding
1909   // the Threads_lock which ensures we are outside a safepoint. We
1910   // cannot do the obvious and set the active field of the SATB queue
1911   // when the thread is created given that, in some cases, safepoints
1912   // might happen between the JavaThread constructor being called and the
1913   // thread being added to the Java thread list (an example of this is
1914   // when the structure for the DestroyJavaVM thread is created).
1915 #if INCLUDE_ALL_GCS
1916   void initialize_queues();
1917 #else  // INCLUDE_ALL_GCS
1918   void initialize_queues() { }
1919 #endif // INCLUDE_ALL_GCS
1920 
1921   // Machine dependent stuff
1922 #include OS_CPU_HEADER(thread)
1923 
1924  public:
1925   void set_blocked_on_compilation(bool value) {
1926     _blocked_on_compilation = value;
1927   }
1928 
1929   bool blocked_on_compilation() {
1930     return _blocked_on_compilation;
1931   }
1932  protected:
1933   bool         _blocked_on_compilation;
1934 
1935 
1936   // JSR166 per-thread parker
1937  private:
1938   Parker*    _parker;
1939  public:
1940   Parker*     parker() { return _parker; }
1941 
1942   // Biased locking support
1943  private:
1944   GrowableArray<MonitorInfo*>* _cached_monitor_info;
1945  public:
1946   GrowableArray<MonitorInfo*>* cached_monitor_info() { return _cached_monitor_info; }
1947   void set_cached_monitor_info(GrowableArray<MonitorInfo*>* info) { _cached_monitor_info = info; }
1948 
1949   // clearing/querying jni attach status
1950   bool is_attaching_via_jni() const { return _jni_attach_state == _attaching_via_jni; }
1951   bool has_attached_via_jni() const { return is_attaching_via_jni() || _jni_attach_state == _attached_via_jni; }
1952   inline void set_done_attaching_via_jni();
1953 };
1954 
1955 // Inline implementation of JavaThread::current
1956 inline JavaThread* JavaThread::current() {
1957   Thread* thread = Thread::current();
1958   assert(thread->is_Java_thread(), "just checking");
1959   return (JavaThread*)thread;
1960 }
1961 
1962 inline CompilerThread* JavaThread::as_CompilerThread() {
1963   assert(is_Compiler_thread(), "just checking");
1964   return (CompilerThread*)this;
1965 }
1966 
1967 // Dedicated thread to sweep the code cache
1968 class CodeCacheSweeperThread : public JavaThread {
1969   CompiledMethod*       _scanned_compiled_method; // nmethod being scanned by the sweeper
1970  public:
1971   CodeCacheSweeperThread();
1972   // Track the nmethod currently being scanned by the sweeper
1973   void set_scanned_compiled_method(CompiledMethod* cm) {
1974     assert(_scanned_compiled_method == NULL || cm == NULL, "should reset to NULL before writing a new value");
1975     _scanned_compiled_method = cm;
1976   }
1977 
1978   // Hide sweeper thread from external view.
1979   bool is_hidden_from_external_view() const { return true; }
1980 
1981   bool is_Code_cache_sweeper_thread() const { return true; }
1982 
1983   // Prevent GC from unloading _scanned_compiled_method
1984   void oops_do(OopClosure* f, CodeBlobClosure* cf);
1985   void nmethods_do(CodeBlobClosure* cf);
1986 };
1987 
1988 // A thread used for Compilation.
1989 class CompilerThread : public JavaThread {
1990   friend class VMStructs;
1991  private:
1992   CompilerCounters* _counters;
1993 
1994   ciEnv*            _env;
1995   CompileLog*       _log;
1996   CompileTask*      _task;
1997   CompileQueue*     _queue;
1998   BufferBlob*       _buffer_blob;
1999 
2000   AbstractCompiler* _compiler;
2001 
2002  public:
2003 
2004   static CompilerThread* current();
2005 
2006   CompilerThread(CompileQueue* queue, CompilerCounters* counters);
2007 
2008   bool is_Compiler_thread() const                { return true; }
2009 
2010   virtual bool can_call_java() const;
2011 
2012   // Hide native compiler threads from external view.
2013   bool is_hidden_from_external_view() const      { return !can_call_java(); }
2014 
2015   void set_compiler(AbstractCompiler* c)         { _compiler = c; }
2016   AbstractCompiler* compiler() const             { return _compiler; }
2017 
2018   CompileQueue* queue()        const             { return _queue; }
2019   CompilerCounters* counters() const             { return _counters; }
2020 
2021   // Get/set the thread's compilation environment.
2022   ciEnv*        env()                            { return _env; }
2023   void          set_env(ciEnv* env)              { _env = env; }
2024 
2025   BufferBlob*   get_buffer_blob() const          { return _buffer_blob; }
2026   void          set_buffer_blob(BufferBlob* b)   { _buffer_blob = b; }
2027 
2028   // Get/set the thread's logging information
2029   CompileLog*   log()                            { return _log; }
2030   void          init_log(CompileLog* log) {
2031     // Set once, for good.
2032     assert(_log == NULL, "set only once");
2033     _log = log;
2034   }
2035 
2036 #ifndef PRODUCT
2037  private:
2038   IdealGraphPrinter *_ideal_graph_printer;
2039  public:
2040   IdealGraphPrinter *ideal_graph_printer()           { return _ideal_graph_printer; }
2041   void set_ideal_graph_printer(IdealGraphPrinter *n) { _ideal_graph_printer = n; }
2042 #endif
2043 
2044   // Get/set the thread's current task
2045   CompileTask* task()                      { return _task; }
2046   void         set_task(CompileTask* task) { _task = task; }
2047 };
2048 
2049 inline CompilerThread* CompilerThread::current() {
2050   return JavaThread::current()->as_CompilerThread();
2051 }
2052 
2053 // The active thread queue. It also keeps track of the current used
2054 // thread priorities.
2055 class Threads: AllStatic {
2056   friend class VMStructs;
2057  private:
2058   static JavaThread* _thread_list;
2059   static int         _number_of_threads;
2060   static int         _number_of_non_daemon_threads;
2061   static int         _return_code;
2062   static int         _thread_claim_parity;
2063 #ifdef ASSERT
2064   static bool        _vm_complete;
2065 #endif
2066 
2067   static void initialize_java_lang_classes(JavaThread* main_thread, TRAPS);
2068   static void initialize_jsr292_core_classes(TRAPS);
2069  public:
2070   // Thread management
2071   // force_daemon is a concession to JNI, where we may need to add a
2072   // thread to the thread list before allocating its thread object
2073   static void add(JavaThread* p, bool force_daemon = false);
2074   static void remove(JavaThread* p);
2075   static bool includes(JavaThread* p);
2076   static JavaThread* first()                     { return _thread_list; }
2077   static void threads_do(ThreadClosure* tc);
2078 
2079   // Initializes the vm and creates the vm thread
2080   static jint create_vm(JavaVMInitArgs* args, bool* canTryAgain);
2081   static void convert_vm_init_libraries_to_agents();
2082   static void create_vm_init_libraries();
2083   static void create_vm_init_agents();
2084   static void shutdown_vm_agents();
2085   static bool destroy_vm();
2086   // Supported VM versions via JNI
2087   // Includes JNI_VERSION_1_1
2088   static jboolean is_supported_jni_version_including_1_1(jint version);
2089   // Does not include JNI_VERSION_1_1
2090   static jboolean is_supported_jni_version(jint version);
2091 
2092   // The "thread claim parity" provides a way for threads to be claimed
2093   // by parallel worker tasks.
2094   //
2095   // Each thread contains a a "parity" field. A task will claim the
2096   // thread only if its parity field is the same as the global parity,
2097   // which is updated by calling change_thread_claim_parity().
2098   //
2099   // For this to work change_thread_claim_parity() needs to be called
2100   // exactly once in sequential code before starting parallel tasks
2101   // that should claim threads.
2102   //
2103   // New threads get their parity set to 0 and change_thread_claim_parity()
2104   // never set the global parity to 0.
2105   static int thread_claim_parity() { return _thread_claim_parity; }
2106   static void change_thread_claim_parity();
2107   static void assert_all_threads_claimed() NOT_DEBUG_RETURN;
2108 
2109   // Apply "f->do_oop" to all root oops in all threads.
2110   // This version may only be called by sequential code.
2111   static void oops_do(OopClosure* f, CodeBlobClosure* cf);
2112   // This version may be called by sequential or parallel code.
2113   static void possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf);
2114   // This creates a list of GCTasks, one per thread.
2115   static void create_thread_roots_tasks(GCTaskQueue* q);
2116   // This creates a list of GCTasks, one per thread, for marking objects.
2117   static void create_thread_roots_marking_tasks(GCTaskQueue* q);
2118 
2119   // Apply "f->do_oop" to roots in all threads that
2120   // are part of compiled frames
2121   static void compiled_frame_oops_do(OopClosure* f, CodeBlobClosure* cf);
2122 
2123   static void convert_hcode_pointers();
2124   static void restore_hcode_pointers();
2125 
2126   // Sweeper
2127   static void nmethods_do(CodeBlobClosure* cf);
2128 
2129   // RedefineClasses support
2130   static void metadata_do(void f(Metadata*));
2131   static void metadata_handles_do(void f(Metadata*));
2132 
2133 #ifdef ASSERT
2134   static bool is_vm_complete() { return _vm_complete; }
2135 #endif
2136 
2137   // Verification
2138   static void verify();
2139   static void print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks);
2140   static void print(bool print_stacks, bool internal_format) {
2141     // this function is only used by debug.cpp
2142     print_on(tty, print_stacks, internal_format, false /* no concurrent lock printed */);
2143   }
2144   static void print_on_error(outputStream* st, Thread* current, char* buf, int buflen);
2145   static void print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
2146                              int buflen, bool* found_current);
2147   static void print_threads_compiling(outputStream* st, char* buf, int buflen);
2148 
2149   // Get Java threads that are waiting to enter a monitor. If doLock
2150   // is true, then Threads_lock is grabbed as needed. Otherwise, the
2151   // VM needs to be at a safepoint.
2152   static GrowableArray<JavaThread*>* get_pending_threads(int count,
2153                                                          address monitor, bool doLock);
2154 
2155   // Get owning Java thread from the monitor's owner field. If doLock
2156   // is true, then Threads_lock is grabbed as needed. Otherwise, the
2157   // VM needs to be at a safepoint.
2158   static JavaThread *owning_thread_from_monitor_owner(address owner,
2159                                                       bool doLock);
2160 
2161   // Number of threads on the active threads list
2162   static int number_of_threads()                 { return _number_of_threads; }
2163   // Number of non-daemon threads on the active threads list
2164   static int number_of_non_daemon_threads()      { return _number_of_non_daemon_threads; }
2165 
2166   // Deoptimizes all frames tied to marked nmethods
2167   static void deoptimized_wrt_marked_nmethods();
2168 
2169   static JavaThread* find_java_thread_from_java_tid(jlong java_tid);
2170 
2171 };
2172 
2173 
2174 // Thread iterator
2175 class ThreadClosure: public StackObj {
2176  public:
2177   virtual void do_thread(Thread* thread) = 0;
2178 };
2179 
2180 class SignalHandlerMark: public StackObj {
2181  private:
2182   Thread* _thread;
2183  public:
2184   SignalHandlerMark(Thread* t) {
2185     _thread = t;
2186     if (_thread) _thread->enter_signal_handler();
2187   }
2188   ~SignalHandlerMark() {
2189     if (_thread) _thread->leave_signal_handler();
2190     _thread = NULL;
2191   }
2192 };
2193 
2194 
2195 #endif // SHARE_VM_RUNTIME_THREAD_HPP