1 /*
   2  * Copyright (c) 1997, 2010, 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 "memory/allocation.hpp"
  29 #include "memory/threadLocalAllocBuffer.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/safepoint.hpp"
  40 #include "runtime/stubRoutines.hpp"
  41 #include "runtime/threadLocalStorage.hpp"
  42 #include "runtime/unhandledOops.hpp"
  43 #include "utilities/exceptions.hpp"
  44 #include "utilities/top.hpp"
  45 #ifndef SERIALGC
  46 #include "gc_implementation/g1/dirtyCardQueue.hpp"
  47 #include "gc_implementation/g1/satbQueue.hpp"
  48 #endif
  49 #ifdef ZERO
  50 #ifdef TARGET_ARCH_zero
  51 # include "stack_zero.hpp"
  52 #endif
  53 #endif
  54 
  55 class ThreadSafepointState;
  56 class ThreadProfiler;
  57 
  58 class JvmtiThreadState;
  59 class JvmtiGetLoadedClassesClosure;
  60 class ThreadStatistics;
  61 class ConcurrentLocksDump;
  62 class ParkEvent ;
  63 
  64 class ciEnv;
  65 class CompileThread;
  66 class CompileLog;
  67 class CompileTask;
  68 class CompileQueue;
  69 class CompilerCounters;
  70 class vframeArray;
  71 
  72 class DeoptResourceMark;
  73 class jvmtiDeferredLocalVariableSet;
  74 
  75 class GCTaskQueue;
  76 class ThreadClosure;
  77 class IdealGraphPrinter;
  78 
  79 // Class hierarchy
  80 // - Thread
  81 //   - NamedThread
  82 //     - VMThread
  83 //     - ConcurrentGCThread
  84 //     - WorkerThread
  85 //       - GangWorker
  86 //       - GCTaskThread
  87 //   - JavaThread
  88 //   - WatcherThread
  89 
  90 class Thread: public ThreadShadow {
  91   friend class VMStructs;
  92  private:
  93   // Exception handling
  94   // (Note: _pending_exception and friends are in ThreadShadow)
  95   //oop       _pending_exception;                // pending exception for current thread
  96   // const char* _exception_file;                   // file information for exception (debugging only)
  97   // int         _exception_line;                   // line information for exception (debugging only)
  98 
  99   // Support for forcing alignment of thread objects for biased locking
 100   void*       _real_malloc_address;
 101  public:
 102   void* operator new(size_t size);
 103   void  operator delete(void* p);
 104  private:
 105 
 106   // ***************************************************************
 107   // Suspend and resume support
 108   // ***************************************************************
 109   //
 110   // VM suspend/resume no longer exists - it was once used for various
 111   // things including safepoints but was deprecated and finally removed
 112   // in Java 7. Because VM suspension was considered "internal" Java-level
 113   // suspension was considered "external", and this legacy naming scheme
 114   // remains.
 115   //
 116   // External suspend/resume requests come from JVM_SuspendThread,
 117   // JVM_ResumeThread, JVMTI SuspendThread, and finally JVMTI
 118   // ResumeThread. External
 119   // suspend requests cause _external_suspend to be set and external
 120   // resume requests cause _external_suspend to be cleared.
 121   // External suspend requests do not nest on top of other external
 122   // suspend requests. The higher level APIs reject suspend requests
 123   // for already suspended threads.
 124   //
 125   // The external_suspend
 126   // flag is checked by has_special_runtime_exit_condition() and java thread
 127   // will self-suspend when handle_special_runtime_exit_condition() is
 128   // called. Most uses of the _thread_blocked state in JavaThreads are
 129   // considered the same as being externally suspended; if the blocking
 130   // condition lifts, the JavaThread will self-suspend. Other places
 131   // where VM checks for external_suspend include:
 132   //   + mutex granting (do not enter monitors when thread is suspended)
 133   //   + state transitions from _thread_in_native
 134   //
 135   // In general, java_suspend() does not wait for an external suspend
 136   // request to complete. When it returns, the only guarantee is that
 137   // the _external_suspend field is true.
 138   //
 139   // wait_for_ext_suspend_completion() is used to wait for an external
 140   // suspend request to complete. External suspend requests are usually
 141   // followed by some other interface call that requires the thread to
 142   // be quiescent, e.g., GetCallTrace(). By moving the "wait time" into
 143   // the interface that requires quiescence, we give the JavaThread a
 144   // chance to self-suspend before we need it to be quiescent. This
 145   // improves overall suspend/query performance.
 146   //
 147   // _suspend_flags controls the behavior of java_ suspend/resume.
 148   // It must be set under the protection of SR_lock. Read from the flag is
 149   // OK without SR_lock as long as the value is only used as a hint.
 150   // (e.g., check _external_suspend first without lock and then recheck
 151   // inside SR_lock and finish the suspension)
 152   //
 153   // _suspend_flags is also overloaded for other "special conditions" so
 154   // that a single check indicates whether any special action is needed
 155   // eg. for async exceptions.
 156   // -------------------------------------------------------------------
 157   // Notes:
 158   // 1. The suspend/resume logic no longer uses ThreadState in OSThread
 159   // but we still update its value to keep other part of the system (mainly
 160   // JVMTI) happy. ThreadState is legacy code (see notes in
 161   // osThread.hpp).
 162   //
 163   // 2. It would be more natural if set_external_suspend() is private and
 164   // part of java_suspend(), but that probably would affect the suspend/query
 165   // performance. Need more investigation on this.
 166   //
 167 
 168   // suspend/resume lock: used for self-suspend
 169   Monitor*    _SR_lock;
 170 
 171  protected:
 172   enum SuspendFlags {
 173     // NOTE: avoid using the sign-bit as cc generates different test code
 174     //       when the sign-bit is used, and sometimes incorrectly - see CR 6398077
 175 
 176     _external_suspend       = 0x20000000U, // thread is asked to self suspend
 177     _ext_suspended          = 0x40000000U, // thread has self-suspended
 178     _deopt_suspend          = 0x10000000U, // thread needs to self suspend for deopt
 179 
 180     _has_async_exception    = 0x00000001U  // there is a pending async exception
 181   };
 182 
 183   // various suspension related flags - atomically updated
 184   // overloaded for async exception checking in check_special_condition_for_native_trans.
 185   volatile uint32_t _suspend_flags;
 186 
 187  private:
 188   int _num_nested_signal;
 189 
 190  public:
 191   void enter_signal_handler() { _num_nested_signal++; }
 192   void leave_signal_handler() { _num_nested_signal--; }
 193   bool is_inside_signal_handler() const  { return _num_nested_signal > 0; }
 194 
 195  private:
 196   // Debug tracing
 197   static void trace(const char* msg, const Thread* const thread) PRODUCT_RETURN;
 198 
 199   // Active_handles points to a block of handles
 200   JNIHandleBlock* _active_handles;
 201 
 202   // One-element thread local free list
 203   JNIHandleBlock* _free_handle_block;
 204 
 205   // Point to the last handle mark
 206   HandleMark* _last_handle_mark;
 207 
 208   // The parity of the last strong_roots iteration in which this thread was
 209   // claimed as a task.
 210   jint _oops_do_parity;
 211 
 212   public:
 213    void set_last_handle_mark(HandleMark* mark)   { _last_handle_mark = mark; }
 214     HandleMark* last_handle_mark() const          { return _last_handle_mark; }
 215   private:
 216 
 217   // debug support for checking if code does allow safepoints or not
 218   // GC points in the VM can happen because of allocation, invoking a VM operation, or blocking on
 219   // mutex, or blocking on an object synchronizer (Java locking).
 220   // If !allow_safepoint(), then an assertion failure will happen in any of the above cases
 221   // If !allow_allocation(), then an assertion failure will happen during allocation
 222   // (Hence, !allow_safepoint() => !allow_allocation()).
 223   //
 224   // The two classes No_Safepoint_Verifier and No_Allocation_Verifier are used to set these counters.
 225   //
 226   NOT_PRODUCT(int _allow_safepoint_count;)       // If 0, thread allow a safepoint to happen
 227   debug_only (int _allow_allocation_count;)      // If 0, the thread is allowed to allocate oops.
 228 
 229   // Used by SkipGCALot class.
 230   NOT_PRODUCT(bool _skip_gcalot;)                // Should we elide gc-a-lot?
 231 
 232   // Record when GC is locked out via the GC_locker mechanism
 233   CHECK_UNHANDLED_OOPS_ONLY(int _gc_locked_out_count;)
 234 
 235   friend class No_Alloc_Verifier;
 236   friend class No_Safepoint_Verifier;
 237   friend class Pause_No_Safepoint_Verifier;
 238   friend class ThreadLocalStorage;
 239   friend class GC_locker;
 240 
 241   ThreadLocalAllocBuffer _tlab;                  // Thread-local eden
 242 
 243   int   _vm_operation_started_count;             // VM_Operation support
 244   int   _vm_operation_completed_count;           // VM_Operation support
 245 
 246   ObjectMonitor* _current_pending_monitor;       // ObjectMonitor this thread
 247                                                  // is waiting to lock
 248   bool _current_pending_monitor_is_from_java;    // locking is from Java code
 249 
 250   // ObjectMonitor on which this thread called Object.wait()
 251   ObjectMonitor* _current_waiting_monitor;
 252 
 253   // Private thread-local objectmonitor list - a simple cache organized as a SLL.
 254  public:
 255   ObjectMonitor * omFreeList ;
 256   int omFreeCount ;                             // length of omFreeList
 257   int omFreeProvision ;                         // reload chunk size
 258   ObjectMonitor * omInUseList;                  // SLL to track monitors in circulation
 259   int omInUseCount;                             // length of omInUseList
 260 
 261  public:
 262   enum {
 263     is_definitely_current_thread = true
 264   };
 265 
 266   // Constructor
 267   Thread();
 268   virtual ~Thread();
 269 
 270   // initializtion
 271   void initialize_thread_local_storage();
 272 
 273   // thread entry point
 274   virtual void run();
 275 
 276   // Testers
 277   virtual bool is_VM_thread()       const            { return false; }
 278   virtual bool is_Java_thread()     const            { return false; }
 279   // Remove this ifdef when C1 is ported to the compiler interface.
 280   virtual bool is_Compiler_thread() const            { return false; }
 281   virtual bool is_hidden_from_external_view() const  { return false; }
 282   virtual bool is_jvmti_agent_thread() const         { return false; }
 283   // True iff the thread can perform GC operations at a safepoint.
 284   // Generally will be true only of VM thread and parallel GC WorkGang
 285   // threads.
 286   virtual bool is_GC_task_thread() const             { return false; }
 287   virtual bool is_Watcher_thread() const             { return false; }
 288   virtual bool is_ConcurrentGC_thread() const        { return false; }
 289   virtual bool is_Named_thread() const               { return false; }
 290 
 291   virtual char* name() const { return (char*)"Unknown thread"; }
 292 
 293   // Returns the current thread
 294   static inline Thread* current();
 295 
 296   // Common thread operations
 297   static void set_priority(Thread* thread, ThreadPriority priority);
 298   static ThreadPriority get_priority(const Thread* const thread);
 299   static void start(Thread* thread);
 300   static void interrupt(Thread* thr);
 301   static bool is_interrupted(Thread* thr, bool clear_interrupted);
 302 
 303   ObjectMonitor** omInUseList_addr()             { return (ObjectMonitor **)&omInUseList; }
 304   Monitor* SR_lock() const                       { return _SR_lock; }
 305 
 306   bool has_async_exception() const { return (_suspend_flags & _has_async_exception) != 0; }
 307 
 308   void set_suspend_flag(SuspendFlags f) {
 309     assert(sizeof(jint) == sizeof(_suspend_flags), "size mismatch");
 310     uint32_t flags;
 311     do {
 312       flags = _suspend_flags;
 313     }
 314     while (Atomic::cmpxchg((jint)(flags | f),
 315                            (volatile jint*)&_suspend_flags,
 316                            (jint)flags) != (jint)flags);
 317   }
 318   void clear_suspend_flag(SuspendFlags f) {
 319     assert(sizeof(jint) == sizeof(_suspend_flags), "size mismatch");
 320     uint32_t flags;
 321     do {
 322       flags = _suspend_flags;
 323     }
 324     while (Atomic::cmpxchg((jint)(flags & ~f),
 325                            (volatile jint*)&_suspend_flags,
 326                            (jint)flags) != (jint)flags);
 327   }
 328 
 329   void set_has_async_exception() {
 330     set_suspend_flag(_has_async_exception);
 331   }
 332   void clear_has_async_exception() {
 333     clear_suspend_flag(_has_async_exception);
 334   }
 335 
 336   // Support for Unhandled Oop detection
 337 #ifdef CHECK_UNHANDLED_OOPS
 338  private:
 339   UnhandledOops *_unhandled_oops;
 340  public:
 341   UnhandledOops* unhandled_oops()               { return _unhandled_oops; }
 342   // Mark oop safe for gc.  It may be stack allocated but won't move.
 343   void allow_unhandled_oop(oop *op)              {
 344     if (CheckUnhandledOops) unhandled_oops()->allow_unhandled_oop(op);
 345   }
 346   // Clear oops at safepoint so crashes point to unhandled oop violator
 347   void clear_unhandled_oops()                   {
 348     if (CheckUnhandledOops) unhandled_oops()->clear_unhandled_oops();
 349   }
 350   bool is_gc_locked_out() { return _gc_locked_out_count > 0; }
 351 #endif // CHECK_UNHANDLED_OOPS
 352 
 353 #ifndef PRODUCT
 354   bool skip_gcalot()           { return _skip_gcalot; }
 355   void set_skip_gcalot(bool v) { _skip_gcalot = v;    }
 356 #endif
 357 
 358  public:
 359   // Installs a pending exception to be inserted later
 360   static void send_async_exception(oop thread_oop, oop java_throwable);
 361 
 362   // Resource area
 363   ResourceArea* resource_area() const            { return _resource_area; }
 364   void set_resource_area(ResourceArea* area)     { _resource_area = area; }
 365 
 366   OSThread* osthread() const                     { return _osthread;   }
 367   void set_osthread(OSThread* thread)            { _osthread = thread; }
 368 
 369   // JNI handle support
 370   JNIHandleBlock* active_handles() const         { return _active_handles; }
 371   void set_active_handles(JNIHandleBlock* block) { _active_handles = block; }
 372   JNIHandleBlock* free_handle_block() const      { return _free_handle_block; }
 373   void set_free_handle_block(JNIHandleBlock* block) { _free_handle_block = block; }
 374 
 375   // Internal handle support
 376   HandleArea* handle_area() const                { return _handle_area; }
 377   void set_handle_area(HandleArea* area)         { _handle_area = area; }
 378 
 379   // Thread-Local Allocation Buffer (TLAB) support
 380   ThreadLocalAllocBuffer& tlab()                 { return _tlab; }
 381   void initialize_tlab() {
 382     if (UseTLAB) {
 383       tlab().initialize();
 384     }
 385   }
 386 
 387   // VM operation support
 388   int vm_operation_ticket()                      { return ++_vm_operation_started_count; }
 389   int vm_operation_completed_count()             { return _vm_operation_completed_count; }
 390   void increment_vm_operation_completed_count()  { _vm_operation_completed_count++; }
 391 
 392   // For tracking the heavyweight monitor the thread is pending on.
 393   ObjectMonitor* current_pending_monitor() {
 394     return _current_pending_monitor;
 395   }
 396   void set_current_pending_monitor(ObjectMonitor* monitor) {
 397     _current_pending_monitor = monitor;
 398   }
 399   void set_current_pending_monitor_is_from_java(bool from_java) {
 400     _current_pending_monitor_is_from_java = from_java;
 401   }
 402   bool current_pending_monitor_is_from_java() {
 403     return _current_pending_monitor_is_from_java;
 404   }
 405 
 406   // For tracking the ObjectMonitor on which this thread called Object.wait()
 407   ObjectMonitor* current_waiting_monitor() {
 408     return _current_waiting_monitor;
 409   }
 410   void set_current_waiting_monitor(ObjectMonitor* monitor) {
 411     _current_waiting_monitor = monitor;
 412   }
 413 
 414   // GC support
 415   // Apply "f->do_oop" to all root oops in "this".
 416   // Apply "cf->do_code_blob" (if !NULL) to all code blobs active in frames
 417   void oops_do(OopClosure* f, CodeBlobClosure* cf);
 418 
 419   // Handles the parallel case for the method below.
 420 private:
 421   bool claim_oops_do_par_case(int collection_parity);
 422 public:
 423   // Requires that "collection_parity" is that of the current strong roots
 424   // iteration.  If "is_par" is false, sets the parity of "this" to
 425   // "collection_parity", and returns "true".  If "is_par" is true,
 426   // uses an atomic instruction to set the current threads parity to
 427   // "collection_parity", if it is not already.  Returns "true" iff the
 428   // calling thread does the update, this indicates that the calling thread
 429   // has claimed the thread's stack as a root groop in the current
 430   // collection.
 431   bool claim_oops_do(bool is_par, int collection_parity) {
 432     if (!is_par) {
 433       _oops_do_parity = collection_parity;
 434       return true;
 435     } else {
 436       return claim_oops_do_par_case(collection_parity);
 437     }
 438   }
 439 
 440   // Sweeper support
 441   void nmethods_do(CodeBlobClosure* cf);
 442 
 443   // Used by fast lock support
 444   virtual bool is_lock_owned(address adr) const;
 445 
 446   // Check if address is in the stack of the thread (not just for locks).
 447   // Warning: the method can only be used on the running thread
 448   bool is_in_stack(address adr) const;
 449 
 450   // Sets this thread as starting thread. Returns failure if thread
 451   // creation fails due to lack of memory, too many threads etc.
 452   bool set_as_starting_thread();
 453 
 454  protected:
 455   // OS data associated with the thread
 456   OSThread* _osthread;  // Platform-specific thread information
 457 
 458   // Thread local resource area for temporary allocation within the VM
 459   ResourceArea* _resource_area;
 460 
 461   // Thread local handle area for allocation of handles within the VM
 462   HandleArea* _handle_area;
 463 
 464   // Support for stack overflow handling, get_thread, etc.
 465   address          _stack_base;
 466   size_t           _stack_size;
 467   uintptr_t        _self_raw_id;      // used by get_thread (mutable)
 468   int              _lgrp_id;
 469 
 470  public:
 471   // Stack overflow support
 472   address stack_base() const           { assert(_stack_base != NULL,"Sanity check"); return _stack_base; }
 473 
 474   void    set_stack_base(address base) { _stack_base = base; }
 475   size_t  stack_size() const           { return _stack_size; }
 476   void    set_stack_size(size_t size)  { _stack_size = size; }
 477   void    record_stack_base_and_size();
 478 
 479   bool    on_local_stack(address adr) const {
 480     /* QQQ this has knowledge of direction, ought to be a stack method */
 481     return (_stack_base >= adr && adr >= (_stack_base - _stack_size));
 482   }
 483 
 484   int     lgrp_id() const                 { return _lgrp_id; }
 485   void    set_lgrp_id(int value)          { _lgrp_id = value; }
 486 
 487   // Printing
 488   void print_on(outputStream* st) const;
 489   void print() const { print_on(tty); }
 490   virtual void print_on_error(outputStream* st, char* buf, int buflen) const;
 491 
 492   // Debug-only code
 493 
 494 #ifdef ASSERT
 495  private:
 496   // Deadlock detection support for Mutex locks. List of locks own by thread.
 497   Monitor *_owned_locks;
 498   // Mutex::set_owner_implementation is the only place where _owned_locks is modified,
 499   // thus the friendship
 500   friend class Mutex;
 501   friend class Monitor;
 502 
 503  public:
 504   void print_owned_locks_on(outputStream* st) const;
 505   void print_owned_locks() const                 { print_owned_locks_on(tty);    }
 506   Monitor * owned_locks() const                  { return _owned_locks;          }
 507   bool owns_locks() const                        { return owned_locks() != NULL; }
 508   bool owns_locks_but_compiled_lock() const;
 509 
 510   // Deadlock detection
 511   bool allow_allocation()                        { return _allow_allocation_count == 0; }
 512 #endif
 513 
 514   void check_for_valid_safepoint_state(bool potential_vm_operation) PRODUCT_RETURN;
 515 
 516  private:
 517   volatile int _jvmti_env_iteration_count;
 518 
 519  public:
 520   void entering_jvmti_env_iteration()            { ++_jvmti_env_iteration_count; }
 521   void leaving_jvmti_env_iteration()             { --_jvmti_env_iteration_count; }
 522   bool is_inside_jvmti_env_iteration()           { return _jvmti_env_iteration_count > 0; }
 523 
 524   // Code generation
 525   static ByteSize exception_file_offset()        { return byte_offset_of(Thread, _exception_file   ); }
 526   static ByteSize exception_line_offset()        { return byte_offset_of(Thread, _exception_line   ); }
 527   static ByteSize active_handles_offset()        { return byte_offset_of(Thread, _active_handles   ); }
 528 
 529   static ByteSize stack_base_offset()            { return byte_offset_of(Thread, _stack_base ); }
 530   static ByteSize stack_size_offset()            { return byte_offset_of(Thread, _stack_size ); }
 531 
 532 #define TLAB_FIELD_OFFSET(name) \
 533   static ByteSize tlab_##name##_offset()            { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::name##_offset(); }
 534 
 535   TLAB_FIELD_OFFSET(start)
 536   TLAB_FIELD_OFFSET(end)
 537   TLAB_FIELD_OFFSET(top)
 538   TLAB_FIELD_OFFSET(pf_top)
 539   TLAB_FIELD_OFFSET(size)                   // desired_size
 540   TLAB_FIELD_OFFSET(refill_waste_limit)
 541   TLAB_FIELD_OFFSET(number_of_refills)
 542   TLAB_FIELD_OFFSET(fast_refill_waste)
 543   TLAB_FIELD_OFFSET(slow_allocations)
 544 
 545 #undef TLAB_FIELD_OFFSET
 546 
 547  public:
 548   volatile intptr_t _Stalled ;
 549   volatile int _TypeTag ;
 550   ParkEvent * _ParkEvent ;                     // for synchronized()
 551   ParkEvent * _SleepEvent ;                    // for Thread.sleep
 552   ParkEvent * _MutexEvent ;                    // for native internal Mutex/Monitor
 553   ParkEvent * _MuxEvent ;                      // for low-level muxAcquire-muxRelease
 554   int NativeSyncRecursion ;                    // diagnostic
 555 
 556   volatile int _OnTrap ;                       // Resume-at IP delta
 557   jint _hashStateW ;                           // Marsaglia Shift-XOR thread-local RNG
 558   jint _hashStateX ;                           // thread-specific hashCode generator state
 559   jint _hashStateY ;
 560   jint _hashStateZ ;
 561   void * _schedctl ;
 562 
 563   intptr_t _ScratchA, _ScratchB ;              // Scratch locations for fast-path sync code
 564   static ByteSize ScratchA_offset()            { return byte_offset_of(Thread, _ScratchA ); }
 565   static ByteSize ScratchB_offset()            { return byte_offset_of(Thread, _ScratchB ); }
 566 
 567   volatile jint rng [4] ;                      // RNG for spin loop
 568 
 569   // Low-level leaf-lock primitives used to implement synchronization
 570   // and native monitor-mutex infrastructure.
 571   // Not for general synchronization use.
 572   static void SpinAcquire (volatile int * Lock, const char * Name) ;
 573   static void SpinRelease (volatile int * Lock) ;
 574   static void muxAcquire  (volatile intptr_t * Lock, const char * Name) ;
 575   static void muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) ;
 576   static void muxRelease  (volatile intptr_t * Lock) ;
 577 
 578 };
 579 
 580 // Inline implementation of Thread::current()
 581 // Thread::current is "hot" it's called > 128K times in the 1st 500 msecs of
 582 // startup.
 583 // ThreadLocalStorage::thread is warm -- it's called > 16K times in the same
 584 // period.   This is inlined in thread_<os_family>.inline.hpp.
 585 
 586 inline Thread* Thread::current() {
 587 #ifdef ASSERT
 588 // This function is very high traffic. Define PARANOID to enable expensive
 589 // asserts.
 590 #ifdef PARANOID
 591   // Signal handler should call ThreadLocalStorage::get_thread_slow()
 592   Thread* t = ThreadLocalStorage::get_thread_slow();
 593   assert(t != NULL && !t->is_inside_signal_handler(),
 594          "Don't use Thread::current() inside signal handler");
 595 #endif
 596 #endif
 597   Thread* thread = ThreadLocalStorage::thread();
 598   assert(thread != NULL, "just checking");
 599   return thread;
 600 }
 601 
 602 // Name support for threads.  non-JavaThread subclasses with multiple
 603 // uniquely named instances should derive from this.
 604 class NamedThread: public Thread {
 605   friend class VMStructs;
 606   enum {
 607     max_name_len = 64
 608   };
 609  private:
 610   char* _name;
 611   // log JavaThread being processed by oops_do
 612   JavaThread* _processed_thread;
 613 
 614  public:
 615   NamedThread();
 616   ~NamedThread();
 617   // May only be called once per thread.
 618   void set_name(const char* format, ...);
 619   virtual bool is_Named_thread() const { return true; }
 620   virtual char* name() const { return _name == NULL ? (char*)"Unknown Thread" : _name; }
 621   JavaThread *processed_thread() { return _processed_thread; }
 622   void set_processed_thread(JavaThread *thread) { _processed_thread = thread; }
 623 };
 624 
 625 // Worker threads are named and have an id of an assigned work.
 626 class WorkerThread: public NamedThread {
 627 private:
 628   uint _id;
 629 public:
 630   WorkerThread() : _id(0) { }
 631   void set_id(uint work_id) { _id = work_id; }
 632   uint id() const { return _id; }
 633 };
 634 
 635 // A single WatcherThread is used for simulating timer interrupts.
 636 class WatcherThread: public Thread {
 637   friend class VMStructs;
 638  public:
 639   virtual void run();
 640 
 641  private:
 642   static WatcherThread* _watcher_thread;
 643 
 644   volatile static bool _should_terminate; // updated without holding lock
 645  public:
 646   enum SomeConstants {
 647     delay_interval = 10                          // interrupt delay in milliseconds
 648   };
 649 
 650   // Constructor
 651   WatcherThread();
 652 
 653   // Tester
 654   bool is_Watcher_thread() const                 { return true; }
 655 
 656   // Printing
 657   char* name() const { return (char*)"VM Periodic Task Thread"; }
 658   void print_on(outputStream* st) const;
 659   void print() const { print_on(tty); }
 660 
 661   // Returns the single instance of WatcherThread
 662   static WatcherThread* watcher_thread()         { return _watcher_thread; }
 663 
 664   // Create and start the single instance of WatcherThread, or stop it on shutdown
 665   static void start();
 666   static void stop();
 667 };
 668 
 669 
 670 class CompilerThread;
 671 
 672 typedef void (*ThreadFunction)(JavaThread*, TRAPS);
 673 
 674 class JavaThread: public Thread {
 675   friend class VMStructs;
 676  private:
 677   JavaThread*    _next;                          // The next thread in the Threads list
 678   oop            _threadObj;                     // The Java level thread object
 679 
 680 #ifdef ASSERT
 681  private:
 682   int _java_call_counter;
 683 
 684  public:
 685   int  java_call_counter()                       { return _java_call_counter; }
 686   void inc_java_call_counter()                   { _java_call_counter++; }
 687   void dec_java_call_counter() {
 688     assert(_java_call_counter > 0, "Invalid nesting of JavaCallWrapper");
 689     _java_call_counter--;
 690   }
 691  private:  // restore original namespace restriction
 692 #endif  // ifdef ASSERT
 693 
 694 #ifndef PRODUCT
 695  public:
 696   enum {
 697     jump_ring_buffer_size = 16
 698   };
 699  private:  // restore original namespace restriction
 700 #endif
 701 
 702   JavaFrameAnchor _anchor;                       // Encapsulation of current java frame and it state
 703 
 704   ThreadFunction _entry_point;
 705 
 706   JNIEnv        _jni_environment;
 707 
 708   // Deopt support
 709   DeoptResourceMark*  _deopt_mark;               // Holds special ResourceMark for deoptimization
 710 
 711   intptr_t*      _must_deopt_id;                 // id of frame that needs to be deopted once we
 712                                                  // transition out of native
 713 
 714   vframeArray*  _vframe_array_head;              // Holds the heap of the active vframeArrays
 715   vframeArray*  _vframe_array_last;              // Holds last vFrameArray we popped
 716   // Because deoptimization is lazy we must save jvmti requests to set locals
 717   // in compiled frames until we deoptimize and we have an interpreter frame.
 718   // This holds the pointer to array (yeah like there might be more than one) of
 719   // description of compiled vframes that have locals that need to be updated.
 720   GrowableArray<jvmtiDeferredLocalVariableSet*>* _deferred_locals_updates;
 721 
 722   // Handshake value for fixing 6243940. We need a place for the i2c
 723   // adapter to store the callee methodOop. This value is NEVER live
 724   // across a gc point so it does NOT have to be gc'd
 725   // The handshake is open ended since we can't be certain that it will
 726   // be NULLed. This is because we rarely ever see the race and end up
 727   // in handle_wrong_method which is the backend of the handshake. See
 728   // code in i2c adapters and handle_wrong_method.
 729 
 730   methodOop     _callee_target;
 731 
 732   // Oop results of VM runtime calls
 733   oop           _vm_result;    // Used to pass back an oop result into Java code, GC-preserved
 734   oop           _vm_result_2;  // Used to pass back an oop result into Java code, GC-preserved
 735 
 736   // See ReduceInitialCardMarks: this holds the precise space interval of
 737   // the most recent slow path allocation for which compiled code has
 738   // elided card-marks for performance along the fast-path.
 739   MemRegion     _deferred_card_mark;
 740 
 741   MonitorChunk* _monitor_chunks;                 // Contains the off stack monitors
 742                                                  // allocated during deoptimization
 743                                                  // and by JNI_MonitorEnter/Exit
 744 
 745   // Async. requests support
 746   enum AsyncRequests {
 747     _no_async_condition = 0,
 748     _async_exception,
 749     _async_unsafe_access_error
 750   };
 751   AsyncRequests _special_runtime_exit_condition; // Enum indicating pending async. request
 752   oop           _pending_async_exception;
 753 
 754   // Safepoint support
 755  public:                                         // Expose _thread_state for SafeFetchInt()
 756   volatile JavaThreadState _thread_state;
 757  private:
 758   ThreadSafepointState *_safepoint_state;        // Holds information about a thread during a safepoint
 759   address               _saved_exception_pc;     // Saved pc of instruction where last implicit exception happened
 760 
 761   // JavaThread termination support
 762   enum TerminatedTypes {
 763     _not_terminated = 0xDEAD - 2,
 764     _thread_exiting,                             // JavaThread::exit() has been called for this thread
 765     _thread_terminated,                          // JavaThread is removed from thread list
 766     _vm_exited                                   // JavaThread is still executing native code, but VM is terminated
 767                                                  // only VM_Exit can set _vm_exited
 768   };
 769 
 770   // In general a JavaThread's _terminated field transitions as follows:
 771   //
 772   //   _not_terminated => _thread_exiting => _thread_terminated
 773   //
 774   // _vm_exited is a special value to cover the case of a JavaThread
 775   // executing native code after the VM itself is terminated.
 776   TerminatedTypes       _terminated;
 777   // suspend/resume support
 778   volatile bool         _suspend_equivalent;     // Suspend equivalent condition
 779   jint                  _in_deopt_handler;       // count of deoptimization
 780                                                  // handlers thread is in
 781   volatile bool         _doing_unsafe_access;    // Thread may fault due to unsafe access
 782   bool                  _do_not_unlock_if_synchronized; // Do not unlock the receiver of a synchronized method (since it was
 783                                                  // never locked) when throwing an exception. Used by interpreter only.
 784 
 785   //  Flag to mark a JNI thread in the process of attaching - See CR 6404306
 786   //  This flag is never set true other than at construction, and in that case
 787   //  is shortly thereafter set false
 788   volatile bool _is_attaching;
 789 
 790  public:
 791   // State of the stack guard pages for this thread.
 792   enum StackGuardState {
 793     stack_guard_unused,         // not needed
 794     stack_guard_yellow_disabled,// disabled (temporarily) after stack overflow
 795     stack_guard_enabled         // enabled
 796   };
 797 
 798  private:
 799 
 800   StackGuardState        _stack_guard_state;
 801 
 802   // Compiler exception handling (NOTE: The _exception_oop is *NOT* the same as _pending_exception. It is
 803   // used to temp. parsing values into and out of the runtime system during exception handling for compiled
 804   // code)
 805   volatile oop     _exception_oop;               // Exception thrown in compiled code
 806   volatile address _exception_pc;                // PC where exception happened
 807   volatile address _exception_handler_pc;        // PC for handler of exception
 808   volatile int     _exception_stack_size;        // Size of frame where exception happened
 809   volatile int     _is_method_handle_return;     // true (== 1) if the current exception PC is a MethodHandle call site.
 810 
 811   // support for compilation
 812   bool    _is_compiling;                         // is true if a compilation is active inthis thread (one compilation per thread possible)
 813 
 814   // support for JNI critical regions
 815   jint    _jni_active_critical;                  // count of entries into JNI critical region
 816 
 817   // For deadlock detection.
 818   int _depth_first_number;
 819 
 820   // JVMTI PopFrame support
 821   // This is set to popframe_pending to signal that top Java frame should be popped immediately
 822   int _popframe_condition;
 823 
 824 #ifndef PRODUCT
 825   int _jmp_ring_index;
 826   struct {
 827       // We use intptr_t instead of address so debugger doesn't try and display strings
 828       intptr_t _target;
 829       intptr_t _instruction;
 830       const char*  _file;
 831       int _line;
 832   }   _jmp_ring[ jump_ring_buffer_size ];
 833 #endif /* PRODUCT */
 834 
 835 #ifndef SERIALGC
 836   // Support for G1 barriers
 837 
 838   ObjPtrQueue _satb_mark_queue;          // Thread-local log for SATB barrier.
 839   // Set of all such queues.
 840   static SATBMarkQueueSet _satb_mark_queue_set;
 841 
 842   DirtyCardQueue _dirty_card_queue;      // Thread-local log for dirty cards.
 843   // Set of all such queues.
 844   static DirtyCardQueueSet _dirty_card_queue_set;
 845 
 846   void flush_barrier_queues();
 847 #endif // !SERIALGC
 848 
 849   friend class VMThread;
 850   friend class ThreadWaitTransition;
 851   friend class VM_Exit;
 852 
 853   void initialize();                             // Initialized the instance variables
 854 
 855  public:
 856   // Constructor
 857   JavaThread(bool is_attaching = false); // for main thread and JNI attached threads
 858   JavaThread(ThreadFunction entry_point, size_t stack_size = 0);
 859   ~JavaThread();
 860 
 861 #ifdef ASSERT
 862   // verify this JavaThread hasn't be published in the Threads::list yet
 863   void verify_not_published();
 864 #endif
 865 
 866   //JNI functiontable getter/setter for JVMTI jni function table interception API.
 867   void set_jni_functions(struct JNINativeInterface_* functionTable) {
 868     _jni_environment.functions = functionTable;
 869   }
 870   struct JNINativeInterface_* get_jni_functions() {
 871     return (struct JNINativeInterface_ *)_jni_environment.functions;
 872   }
 873 
 874   // This function is called at thread creation to allow
 875   // platform specific thread variables to be initialized.
 876   void cache_global_variables();
 877 
 878   // Executes Shutdown.shutdown()
 879   void invoke_shutdown_hooks();
 880 
 881   // Cleanup on thread exit
 882   enum ExitType {
 883     normal_exit,
 884     jni_detach
 885   };
 886   void exit(bool destroy_vm, ExitType exit_type = normal_exit);
 887 
 888   void cleanup_failed_attach_current_thread();
 889 
 890   // Testers
 891   virtual bool is_Java_thread() const            { return true;  }
 892 
 893   // compilation
 894   void set_is_compiling(bool f)                  { _is_compiling = f; }
 895   bool is_compiling() const                      { return _is_compiling; }
 896 
 897   // Thread chain operations
 898   JavaThread* next() const                       { return _next; }
 899   void set_next(JavaThread* p)                   { _next = p; }
 900 
 901   // Thread oop. threadObj() can be NULL for initial JavaThread
 902   // (or for threads attached via JNI)
 903   oop threadObj() const                          { return _threadObj; }
 904   void set_threadObj(oop p)                      { _threadObj = p; }
 905 
 906   ThreadPriority java_priority() const;          // Read from threadObj()
 907 
 908   // Prepare thread and add to priority queue.  If a priority is
 909   // not specified, use the priority of the thread object. Threads_lock
 910   // must be held while this function is called.
 911   void prepare(jobject jni_thread, ThreadPriority prio=NoPriority);
 912 
 913   void set_saved_exception_pc(address pc)        { _saved_exception_pc = pc; }
 914   address saved_exception_pc()                   { return _saved_exception_pc; }
 915 
 916 
 917   ThreadFunction entry_point() const             { return _entry_point; }
 918 
 919   // Allocates a new Java level thread object for this thread. thread_name may be NULL.
 920   void allocate_threadObj(Handle thread_group, char* thread_name, bool daemon, TRAPS);
 921 
 922   // Last frame anchor routines
 923 
 924   JavaFrameAnchor* frame_anchor(void)                { return &_anchor; }
 925 
 926   // last_Java_sp
 927   bool has_last_Java_frame() const                   { return _anchor.has_last_Java_frame(); }
 928   intptr_t* last_Java_sp() const                     { return _anchor.last_Java_sp(); }
 929 
 930   // last_Java_pc
 931 
 932   address last_Java_pc(void)                         { return _anchor.last_Java_pc(); }
 933 
 934   // Safepoint support
 935   JavaThreadState thread_state() const           { return _thread_state; }
 936   void set_thread_state(JavaThreadState s)       { _thread_state=s;      }
 937   ThreadSafepointState *safepoint_state() const  { return _safepoint_state;  }
 938   void set_safepoint_state(ThreadSafepointState *state) { _safepoint_state = state; }
 939   bool is_at_poll_safepoint()                    { return _safepoint_state->is_at_poll_safepoint(); }
 940 
 941   // thread has called JavaThread::exit() or is terminated
 942   bool is_exiting()                              { return _terminated == _thread_exiting || is_terminated(); }
 943   // thread is terminated (no longer on the threads list); we compare
 944   // against the two non-terminated values so that a freed JavaThread
 945   // will also be considered terminated.
 946   bool is_terminated()                           { return _terminated != _not_terminated && _terminated != _thread_exiting; }
 947   void set_terminated(TerminatedTypes t)         { _terminated = t; }
 948   // special for Threads::remove() which is static:
 949   void set_terminated_value()                    { _terminated = _thread_terminated; }
 950   void block_if_vm_exited();
 951 
 952   bool doing_unsafe_access()                     { return _doing_unsafe_access; }
 953   void set_doing_unsafe_access(bool val)         { _doing_unsafe_access = val; }
 954 
 955   bool do_not_unlock_if_synchronized()             { return _do_not_unlock_if_synchronized; }
 956   void set_do_not_unlock_if_synchronized(bool val) { _do_not_unlock_if_synchronized = val; }
 957 
 958 
 959   // Suspend/resume support for JavaThread
 960 
 961  private:
 962   void set_ext_suspended()       { set_suspend_flag (_ext_suspended);  }
 963   void clear_ext_suspended()     { clear_suspend_flag(_ext_suspended); }
 964 
 965  public:
 966   void java_suspend();
 967   void java_resume();
 968   int  java_suspend_self();
 969 
 970   void check_and_wait_while_suspended() {
 971     assert(JavaThread::current() == this, "sanity check");
 972 
 973     bool do_self_suspend;
 974     do {
 975       // were we externally suspended while we were waiting?
 976       do_self_suspend = handle_special_suspend_equivalent_condition();
 977       if (do_self_suspend) {
 978         // don't surprise the thread that suspended us by returning
 979         java_suspend_self();
 980         set_suspend_equivalent();
 981       }
 982     } while (do_self_suspend);
 983   }
 984   static void check_safepoint_and_suspend_for_native_trans(JavaThread *thread);
 985   // Check for async exception in addition to safepoint and suspend request.
 986   static void check_special_condition_for_native_trans(JavaThread *thread);
 987 
 988   bool is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits);
 989   bool is_ext_suspend_completed_with_lock(uint32_t *bits) {
 990     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
 991     // Warning: is_ext_suspend_completed() may temporarily drop the
 992     // SR_lock to allow the thread to reach a stable thread state if
 993     // it is currently in a transient thread state.
 994     return is_ext_suspend_completed(false /*!called_by_wait */,
 995                                     SuspendRetryDelay, bits);
 996   }
 997 
 998   // We cannot allow wait_for_ext_suspend_completion() to run forever or
 999   // we could hang. SuspendRetryCount and SuspendRetryDelay are normally
1000   // passed as the count and delay parameters. Experiments with specific
1001   // calls to wait_for_ext_suspend_completion() can be done by passing
1002   // other values in the code. Experiments with all calls can be done
1003   // via the appropriate -XX options.
1004   bool wait_for_ext_suspend_completion(int count, int delay, uint32_t *bits);
1005 
1006   void set_external_suspend()     { set_suspend_flag  (_external_suspend); }
1007   void clear_external_suspend()   { clear_suspend_flag(_external_suspend); }
1008 
1009   void set_deopt_suspend()        { set_suspend_flag  (_deopt_suspend); }
1010   void clear_deopt_suspend()      { clear_suspend_flag(_deopt_suspend); }
1011   bool is_deopt_suspend()         { return (_suspend_flags & _deopt_suspend) != 0; }
1012 
1013   bool is_external_suspend() const {
1014     return (_suspend_flags & _external_suspend) != 0;
1015   }
1016   // Whenever a thread transitions from native to vm/java it must suspend
1017   // if external|deopt suspend is present.
1018   bool is_suspend_after_native() const {
1019     return (_suspend_flags & (_external_suspend | _deopt_suspend) ) != 0;
1020   }
1021 
1022   // external suspend request is completed
1023   bool is_ext_suspended() const {
1024     return (_suspend_flags & _ext_suspended) != 0;
1025   }
1026 
1027   bool is_external_suspend_with_lock() const {
1028     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1029     return is_external_suspend();
1030   }
1031 
1032   // Special method to handle a pending external suspend request
1033   // when a suspend equivalent condition lifts.
1034   bool handle_special_suspend_equivalent_condition() {
1035     assert(is_suspend_equivalent(),
1036       "should only be called in a suspend equivalence condition");
1037     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1038     bool ret = is_external_suspend();
1039     if (!ret) {
1040       // not about to self-suspend so clear suspend equivalence
1041       clear_suspend_equivalent();
1042     }
1043     // implied else:
1044     // We have a pending external suspend request so we leave the
1045     // suspend_equivalent flag set until java_suspend_self() sets
1046     // the ext_suspended flag and clears the suspend_equivalent
1047     // flag. This insures that wait_for_ext_suspend_completion()
1048     // will return consistent values.
1049     return ret;
1050   }
1051 
1052   // utility methods to see if we are doing some kind of suspension
1053   bool is_being_ext_suspended() const            {
1054     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1055     return is_ext_suspended() || is_external_suspend();
1056   }
1057 
1058   bool is_suspend_equivalent() const             { return _suspend_equivalent; }
1059 
1060   void set_suspend_equivalent()                  { _suspend_equivalent = true; };
1061   void clear_suspend_equivalent()                { _suspend_equivalent = false; };
1062 
1063   // Thread.stop support
1064   void send_thread_stop(oop throwable);
1065   AsyncRequests clear_special_runtime_exit_condition() {
1066     AsyncRequests x = _special_runtime_exit_condition;
1067     _special_runtime_exit_condition = _no_async_condition;
1068     return x;
1069   }
1070 
1071   // Are any async conditions present?
1072   bool has_async_condition() { return (_special_runtime_exit_condition != _no_async_condition); }
1073 
1074   void check_and_handle_async_exceptions(bool check_unsafe_error = true);
1075 
1076   // these next two are also used for self-suspension and async exception support
1077   void handle_special_runtime_exit_condition(bool check_asyncs = true);
1078 
1079   // Return true if JavaThread has an asynchronous condition or
1080   // if external suspension is requested.
1081   bool has_special_runtime_exit_condition() {
1082     // We call is_external_suspend() last since external suspend should
1083     // be less common. Because we don't use is_external_suspend_with_lock
1084     // it is possible that we won't see an asynchronous external suspend
1085     // request that has just gotten started, i.e., SR_lock grabbed but
1086     // _external_suspend field change either not made yet or not visible
1087     // yet. However, this is okay because the request is asynchronous and
1088     // we will see the new flag value the next time through. It's also
1089     // possible that the external suspend request is dropped after
1090     // we have checked is_external_suspend(), we will recheck its value
1091     // under SR_lock in java_suspend_self().
1092     return (_special_runtime_exit_condition != _no_async_condition) ||
1093             is_external_suspend() || is_deopt_suspend();
1094   }
1095 
1096   void set_pending_unsafe_access_error()          { _special_runtime_exit_condition = _async_unsafe_access_error; }
1097 
1098   void set_pending_async_exception(oop e) {
1099     _pending_async_exception = e;
1100     _special_runtime_exit_condition = _async_exception;
1101     set_has_async_exception();
1102   }
1103 
1104   // Fast-locking support
1105   bool is_lock_owned(address adr) const;
1106 
1107   // Accessors for vframe array top
1108   // The linked list of vframe arrays are sorted on sp. This means when we
1109   // unpack the head must contain the vframe array to unpack.
1110   void set_vframe_array_head(vframeArray* value) { _vframe_array_head = value; }
1111   vframeArray* vframe_array_head() const         { return _vframe_array_head;  }
1112 
1113   // Side structure for defering update of java frame locals until deopt occurs
1114   GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred_locals() const { return _deferred_locals_updates; }
1115   void set_deferred_locals(GrowableArray<jvmtiDeferredLocalVariableSet *>* vf) { _deferred_locals_updates = vf; }
1116 
1117   // These only really exist to make debugging deopt problems simpler
1118 
1119   void set_vframe_array_last(vframeArray* value) { _vframe_array_last = value; }
1120   vframeArray* vframe_array_last() const         { return _vframe_array_last;  }
1121 
1122   // The special resourceMark used during deoptimization
1123 
1124   void set_deopt_mark(DeoptResourceMark* value)  { _deopt_mark = value; }
1125   DeoptResourceMark* deopt_mark(void)            { return _deopt_mark; }
1126 
1127   intptr_t* must_deopt_id()                      { return _must_deopt_id; }
1128   void     set_must_deopt_id(intptr_t* id)       { _must_deopt_id = id; }
1129   void     clear_must_deopt_id()                 { _must_deopt_id = NULL; }
1130 
1131   methodOop  callee_target() const               { return _callee_target; }
1132   void set_callee_target  (methodOop x)          { _callee_target   = x; }
1133 
1134   // Oop results of vm runtime calls
1135   oop  vm_result() const                         { return _vm_result; }
1136   void set_vm_result  (oop x)                    { _vm_result   = x; }
1137 
1138   oop  vm_result_2() const                       { return _vm_result_2; }
1139   void set_vm_result_2  (oop x)                  { _vm_result_2   = x; }
1140 
1141   MemRegion deferred_card_mark() const           { return _deferred_card_mark; }
1142   void set_deferred_card_mark(MemRegion mr)      { _deferred_card_mark = mr;   }
1143 
1144   // Exception handling for compiled methods
1145   oop      exception_oop() const                 { return _exception_oop; }
1146   int      exception_stack_size() const          { return _exception_stack_size; }
1147   address  exception_pc() const                  { return _exception_pc; }
1148   address  exception_handler_pc() const          { return _exception_handler_pc; }
1149   bool     is_method_handle_return() const       { return _is_method_handle_return == 1; }
1150 
1151   void set_exception_oop(oop o)                  { _exception_oop = o; }
1152   void set_exception_pc(address a)               { _exception_pc = a; }
1153   void set_exception_handler_pc(address a)       { _exception_handler_pc = a; }
1154   void set_exception_stack_size(int size)        { _exception_stack_size = size; }
1155   void set_is_method_handle_return(bool value)   { _is_method_handle_return = value ? 1 : 0; }
1156 
1157   // Stack overflow support
1158   inline size_t stack_available(address cur_sp);
1159   address stack_yellow_zone_base()
1160     { return (address)(stack_base() - (stack_size() - (stack_red_zone_size() + stack_yellow_zone_size()))); }
1161   size_t  stack_yellow_zone_size()
1162     { return StackYellowPages * os::vm_page_size(); }
1163   address stack_red_zone_base()
1164     { return (address)(stack_base() - (stack_size() - stack_red_zone_size())); }
1165   size_t stack_red_zone_size()
1166     { return StackRedPages * os::vm_page_size(); }
1167   bool in_stack_yellow_zone(address a)
1168     { return (a <= stack_yellow_zone_base()) && (a >= stack_red_zone_base()); }
1169   bool in_stack_red_zone(address a)
1170     { return (a <= stack_red_zone_base()) && (a >= (address)((intptr_t)stack_base() - stack_size())); }
1171 
1172   void create_stack_guard_pages();
1173   void remove_stack_guard_pages();
1174 
1175   void enable_stack_yellow_zone();
1176   void disable_stack_yellow_zone();
1177   void enable_stack_red_zone();
1178   void disable_stack_red_zone();
1179 
1180   inline bool stack_yellow_zone_disabled();
1181   inline bool stack_yellow_zone_enabled();
1182 
1183   // Attempt to reguard the stack after a stack overflow may have occurred.
1184   // Returns true if (a) guard pages are not needed on this thread, (b) the
1185   // pages are already guarded, or (c) the pages were successfully reguarded.
1186   // Returns false if there is not enough stack space to reguard the pages, in
1187   // which case the caller should unwind a frame and try again.  The argument
1188   // should be the caller's (approximate) sp.
1189   bool reguard_stack(address cur_sp);
1190   // Similar to above but see if current stackpoint is out of the guard area
1191   // and reguard if possible.
1192   bool reguard_stack(void);
1193 
1194   // Misc. accessors/mutators
1195   void set_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = true; }
1196   void clr_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = false; }
1197   bool do_not_unlock(void)                       { return _do_not_unlock_if_synchronized; }
1198 
1199 #ifndef PRODUCT
1200   void record_jump(address target, address instr, const char* file, int line);
1201 #endif /* PRODUCT */
1202 
1203   // For assembly stub generation
1204   static ByteSize threadObj_offset()             { return byte_offset_of(JavaThread, _threadObj           ); }
1205 #ifndef PRODUCT
1206   static ByteSize jmp_ring_index_offset()        { return byte_offset_of(JavaThread, _jmp_ring_index      ); }
1207   static ByteSize jmp_ring_offset()              { return byte_offset_of(JavaThread, _jmp_ring            ); }
1208 #endif /* PRODUCT */
1209   static ByteSize jni_environment_offset()       { return byte_offset_of(JavaThread, _jni_environment     ); }
1210   static ByteSize last_Java_sp_offset()          {
1211     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset();
1212   }
1213   static ByteSize last_Java_pc_offset()          {
1214     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset();
1215   }
1216   static ByteSize frame_anchor_offset()          {
1217     return byte_offset_of(JavaThread, _anchor);
1218   }
1219   static ByteSize callee_target_offset()         { return byte_offset_of(JavaThread, _callee_target       ); }
1220   static ByteSize vm_result_offset()             { return byte_offset_of(JavaThread, _vm_result           ); }
1221   static ByteSize vm_result_2_offset()           { return byte_offset_of(JavaThread, _vm_result_2         ); }
1222   static ByteSize thread_state_offset()          { return byte_offset_of(JavaThread, _thread_state        ); }
1223   static ByteSize saved_exception_pc_offset()    { return byte_offset_of(JavaThread, _saved_exception_pc  ); }
1224   static ByteSize osthread_offset()              { return byte_offset_of(JavaThread, _osthread            ); }
1225   static ByteSize exception_oop_offset()         { return byte_offset_of(JavaThread, _exception_oop       ); }
1226   static ByteSize exception_pc_offset()          { return byte_offset_of(JavaThread, _exception_pc        ); }
1227   static ByteSize exception_handler_pc_offset()  { return byte_offset_of(JavaThread, _exception_handler_pc); }
1228   static ByteSize exception_stack_size_offset()  { return byte_offset_of(JavaThread, _exception_stack_size); }
1229   static ByteSize is_method_handle_return_offset() { return byte_offset_of(JavaThread, _is_method_handle_return); }
1230   static ByteSize stack_guard_state_offset()     { return byte_offset_of(JavaThread, _stack_guard_state   ); }
1231   static ByteSize suspend_flags_offset()         { return byte_offset_of(JavaThread, _suspend_flags       ); }
1232 
1233   static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
1234   static ByteSize should_post_on_exceptions_flag_offset() {
1235     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
1236   }
1237 
1238 #ifndef SERIALGC
1239   static ByteSize satb_mark_queue_offset()       { return byte_offset_of(JavaThread, _satb_mark_queue); }
1240   static ByteSize dirty_card_queue_offset()      { return byte_offset_of(JavaThread, _dirty_card_queue); }
1241 #endif // !SERIALGC
1242 
1243   // Returns the jni environment for this thread
1244   JNIEnv* jni_environment()                      { return &_jni_environment; }
1245 
1246   static JavaThread* thread_from_jni_environment(JNIEnv* env) {
1247     JavaThread *thread_from_jni_env = (JavaThread*)((intptr_t)env - in_bytes(jni_environment_offset()));
1248     // Only return NULL if thread is off the thread list; starting to
1249     // exit should not return NULL.
1250     if (thread_from_jni_env->is_terminated()) {
1251        thread_from_jni_env->block_if_vm_exited();
1252        return NULL;
1253     } else {
1254        return thread_from_jni_env;
1255     }
1256   }
1257 
1258   // JNI critical regions. These can nest.
1259   bool in_critical()    { return _jni_active_critical > 0; }
1260   void enter_critical() { assert(Thread::current() == this,
1261                                  "this must be current thread");
1262                           _jni_active_critical++; }
1263   void exit_critical()  { assert(Thread::current() == this,
1264                                  "this must be current thread");
1265                           _jni_active_critical--;
1266                           assert(_jni_active_critical >= 0,
1267                                  "JNI critical nesting problem?"); }
1268 
1269   // For deadlock detection
1270   int depth_first_number() { return _depth_first_number; }
1271   void set_depth_first_number(int dfn) { _depth_first_number = dfn; }
1272 
1273  private:
1274   void set_monitor_chunks(MonitorChunk* monitor_chunks) { _monitor_chunks = monitor_chunks; }
1275 
1276  public:
1277   MonitorChunk* monitor_chunks() const           { return _monitor_chunks; }
1278   void add_monitor_chunk(MonitorChunk* chunk);
1279   void remove_monitor_chunk(MonitorChunk* chunk);
1280   bool in_deopt_handler() const                  { return _in_deopt_handler > 0; }
1281   void inc_in_deopt_handler()                    { _in_deopt_handler++; }
1282   void dec_in_deopt_handler()                    {
1283     assert(_in_deopt_handler > 0, "mismatched deopt nesting");
1284     if (_in_deopt_handler > 0) { // robustness
1285       _in_deopt_handler--;
1286     }
1287   }
1288 
1289  private:
1290   void set_entry_point(ThreadFunction entry_point) { _entry_point = entry_point; }
1291 
1292  public:
1293 
1294   // Frame iteration; calls the function f for all frames on the stack
1295   void frames_do(void f(frame*, const RegisterMap*));
1296 
1297   // Memory operations
1298   void oops_do(OopClosure* f, CodeBlobClosure* cf);
1299 
1300   // Sweeper operations
1301   void nmethods_do(CodeBlobClosure* cf);
1302 
1303   // Memory management operations
1304   void gc_epilogue();
1305   void gc_prologue();
1306 
1307   // Misc. operations
1308   char* name() const { return (char*)get_thread_name(); }
1309   void print_on(outputStream* st) const;
1310   void print() const { print_on(tty); }
1311   void print_value();
1312   void print_thread_state_on(outputStream* ) const      PRODUCT_RETURN;
1313   void print_thread_state() const                       PRODUCT_RETURN;
1314   void print_on_error(outputStream* st, char* buf, int buflen) const;
1315   void verify();
1316   const char* get_thread_name() const;
1317 private:
1318   // factor out low-level mechanics for use in both normal and error cases
1319   const char* get_thread_name_string(char* buf = NULL, int buflen = 0) const;
1320 public:
1321   const char* get_threadgroup_name() const;
1322   const char* get_parent_name() const;
1323 
1324   // Accessing frames
1325   frame last_frame() {
1326     _anchor.make_walkable(this);
1327     return pd_last_frame();
1328   }
1329   javaVFrame* last_java_vframe(RegisterMap* reg_map);
1330 
1331   // Returns method at 'depth' java or native frames down the stack
1332   // Used for security checks
1333   klassOop security_get_caller_class(int depth);
1334 
1335   // Print stack trace in external format
1336   void print_stack_on(outputStream* st);
1337   void print_stack() { print_stack_on(tty); }
1338 
1339   // Print stack traces in various internal formats
1340   void trace_stack()                             PRODUCT_RETURN;
1341   void trace_stack_from(vframe* start_vf)        PRODUCT_RETURN;
1342   void trace_frames()                            PRODUCT_RETURN;
1343 
1344   // Returns the number of stack frames on the stack
1345   int depth() const;
1346 
1347   // Function for testing deoptimization
1348   void deoptimize();
1349   void make_zombies();
1350 
1351   void deoptimized_wrt_marked_nmethods();
1352 
1353   // Profiling operation (see fprofile.cpp)
1354  public:
1355    bool profile_last_Java_frame(frame* fr);
1356 
1357  private:
1358    ThreadProfiler* _thread_profiler;
1359  private:
1360    friend class FlatProfiler;                    // uses both [gs]et_thread_profiler.
1361    friend class FlatProfilerTask;                // uses get_thread_profiler.
1362    friend class ThreadProfilerMark;              // uses get_thread_profiler.
1363    ThreadProfiler* get_thread_profiler()         { return _thread_profiler; }
1364    ThreadProfiler* set_thread_profiler(ThreadProfiler* tp) {
1365      ThreadProfiler* result = _thread_profiler;
1366      _thread_profiler = tp;
1367      return result;
1368    }
1369 
1370   // Static operations
1371  public:
1372   // Returns the running thread as a JavaThread
1373   static inline JavaThread* current();
1374 
1375   // Returns the active Java thread.  Do not use this if you know you are calling
1376   // from a JavaThread, as it's slower than JavaThread::current.  If called from
1377   // the VMThread, it also returns the JavaThread that instigated the VMThread's
1378   // operation.  You may not want that either.
1379   static JavaThread* active();
1380 
1381   inline CompilerThread* as_CompilerThread();
1382 
1383  public:
1384   virtual void run();
1385   void thread_main_inner();
1386 
1387  private:
1388   // PRIVILEGED STACK
1389   PrivilegedElement*  _privileged_stack_top;
1390   GrowableArray<oop>* _array_for_gc;
1391  public:
1392 
1393   // Returns the privileged_stack information.
1394   PrivilegedElement* privileged_stack_top() const       { return _privileged_stack_top; }
1395   void set_privileged_stack_top(PrivilegedElement *e)   { _privileged_stack_top = e; }
1396   void register_array_for_gc(GrowableArray<oop>* array) { _array_for_gc = array; }
1397 
1398  public:
1399   // Thread local information maintained by JVMTI.
1400   void set_jvmti_thread_state(JvmtiThreadState *value)                           { _jvmti_thread_state = value; }
1401   // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
1402   // getter is used to get this JavaThread's JvmtiThreadState if it has
1403   // one which means NULL can be returned. JvmtiThreadState::state_for()
1404   // is used to get the specified JavaThread's JvmtiThreadState if it has
1405   // one or it allocates a new JvmtiThreadState for the JavaThread and
1406   // returns it. JvmtiThreadState::state_for() will return NULL only if
1407   // the specified JavaThread is exiting.
1408   JvmtiThreadState *jvmti_thread_state() const                                   { return _jvmti_thread_state; }
1409   static ByteSize jvmti_thread_state_offset()                                    { return byte_offset_of(JavaThread, _jvmti_thread_state); }
1410   void set_jvmti_get_loaded_classes_closure(JvmtiGetLoadedClassesClosure* value) { _jvmti_get_loaded_classes_closure = value; }
1411   JvmtiGetLoadedClassesClosure* get_jvmti_get_loaded_classes_closure() const     { return _jvmti_get_loaded_classes_closure; }
1412 
1413   // JVMTI PopFrame support
1414   // Setting and clearing popframe_condition
1415   // All of these enumerated values are bits. popframe_pending
1416   // indicates that a PopFrame() has been requested and not yet been
1417   // completed. popframe_processing indicates that that PopFrame() is in
1418   // the process of being completed. popframe_force_deopt_reexecution_bit
1419   // indicates that special handling is required when returning to a
1420   // deoptimized caller.
1421   enum PopCondition {
1422     popframe_inactive                      = 0x00,
1423     popframe_pending_bit                   = 0x01,
1424     popframe_processing_bit                = 0x02,
1425     popframe_force_deopt_reexecution_bit   = 0x04
1426   };
1427   PopCondition popframe_condition()                   { return (PopCondition) _popframe_condition; }
1428   void set_popframe_condition(PopCondition c)         { _popframe_condition = c; }
1429   void set_popframe_condition_bit(PopCondition c)     { _popframe_condition |= c; }
1430   void clear_popframe_condition()                     { _popframe_condition = popframe_inactive; }
1431   static ByteSize popframe_condition_offset()         { return byte_offset_of(JavaThread, _popframe_condition); }
1432   bool has_pending_popframe()                         { return (popframe_condition() & popframe_pending_bit) != 0; }
1433   bool popframe_forcing_deopt_reexecution()           { return (popframe_condition() & popframe_force_deopt_reexecution_bit) != 0; }
1434   void clear_popframe_forcing_deopt_reexecution()     { _popframe_condition &= ~popframe_force_deopt_reexecution_bit; }
1435 #ifdef CC_INTERP
1436   bool pop_frame_pending(void)                        { return ((_popframe_condition & popframe_pending_bit) != 0); }
1437   void clr_pop_frame_pending(void)                    { _popframe_condition = popframe_inactive; }
1438   bool pop_frame_in_process(void)                     { return ((_popframe_condition & popframe_processing_bit) != 0); }
1439   void set_pop_frame_in_process(void)                 { _popframe_condition |= popframe_processing_bit; }
1440   void clr_pop_frame_in_process(void)                 { _popframe_condition &= ~popframe_processing_bit; }
1441 #endif
1442 
1443  private:
1444   // Saved incoming arguments to popped frame.
1445   // Used only when popped interpreted frame returns to deoptimized frame.
1446   void*    _popframe_preserved_args;
1447   int      _popframe_preserved_args_size;
1448 
1449  public:
1450   void  popframe_preserve_args(ByteSize size_in_bytes, void* start);
1451   void* popframe_preserved_args();
1452   ByteSize popframe_preserved_args_size();
1453   WordSize popframe_preserved_args_size_in_words();
1454   void  popframe_free_preserved_args();
1455 
1456 
1457  private:
1458   JvmtiThreadState *_jvmti_thread_state;
1459   JvmtiGetLoadedClassesClosure* _jvmti_get_loaded_classes_closure;
1460 
1461   // Used by the interpreter in fullspeed mode for frame pop, method
1462   // entry, method exit and single stepping support. This field is
1463   // only set to non-zero by the VM_EnterInterpOnlyMode VM operation.
1464   // It can be set to zero asynchronously (i.e., without a VM operation
1465   // or a lock) so we have to be very careful.
1466   int               _interp_only_mode;
1467 
1468  public:
1469   // used by the interpreter for fullspeed debugging support (see above)
1470   static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); }
1471   bool is_interp_only_mode()                { return (_interp_only_mode != 0); }
1472   int get_interp_only_mode()                { return _interp_only_mode; }
1473   void increment_interp_only_mode()         { ++_interp_only_mode; }
1474   void decrement_interp_only_mode()         { --_interp_only_mode; }
1475 
1476   // support for cached flag that indicates whether exceptions need to be posted for this thread
1477   // if this is false, we can avoid deoptimizing when events are thrown
1478   // this gets set to reflect whether jvmtiExport::post_exception_throw would actually do anything
1479  private:
1480   int    _should_post_on_exceptions_flag;
1481 
1482  public:
1483   int   should_post_on_exceptions_flag()  { return _should_post_on_exceptions_flag; }
1484   void  set_should_post_on_exceptions_flag(int val)  { _should_post_on_exceptions_flag = val; }
1485 
1486  private:
1487   ThreadStatistics *_thread_stat;
1488 
1489  public:
1490   ThreadStatistics* get_thread_stat() const    { return _thread_stat; }
1491 
1492   // Return a blocker object for which this thread is blocked parking.
1493   oop current_park_blocker();
1494 
1495  private:
1496   static size_t _stack_size_at_create;
1497 
1498  public:
1499   static inline size_t stack_size_at_create(void) {
1500     return _stack_size_at_create;
1501   }
1502   static inline void set_stack_size_at_create(size_t value) {
1503     _stack_size_at_create = value;
1504   }
1505 
1506 #ifndef SERIALGC
1507   // SATB marking queue support
1508   ObjPtrQueue& satb_mark_queue() { return _satb_mark_queue; }
1509   static SATBMarkQueueSet& satb_mark_queue_set() {
1510     return _satb_mark_queue_set;
1511   }
1512 
1513   // Dirty card queue support
1514   DirtyCardQueue& dirty_card_queue() { return _dirty_card_queue; }
1515   static DirtyCardQueueSet& dirty_card_queue_set() {
1516     return _dirty_card_queue_set;
1517   }
1518 #endif // !SERIALGC
1519 
1520   // Machine dependent stuff
1521 #ifdef TARGET_OS_ARCH_linux_x86
1522 # include "thread_linux_x86.hpp"
1523 #endif
1524 #ifdef TARGET_OS_ARCH_linux_sparc
1525 # include "thread_linux_sparc.hpp"
1526 #endif
1527 #ifdef TARGET_OS_ARCH_linux_zero
1528 # include "thread_linux_zero.hpp"
1529 #endif
1530 #ifdef TARGET_OS_ARCH_solaris_x86
1531 # include "thread_solaris_x86.hpp"
1532 #endif
1533 #ifdef TARGET_OS_ARCH_solaris_sparc
1534 # include "thread_solaris_sparc.hpp"
1535 #endif
1536 #ifdef TARGET_OS_ARCH_windows_x86
1537 # include "thread_windows_x86.hpp"
1538 #endif
1539 
1540 
1541  public:
1542   void set_blocked_on_compilation(bool value) {
1543     _blocked_on_compilation = value;
1544   }
1545 
1546   bool blocked_on_compilation() {
1547     return _blocked_on_compilation;
1548   }
1549  protected:
1550   bool         _blocked_on_compilation;
1551 
1552 
1553   // JSR166 per-thread parker
1554 private:
1555   Parker*    _parker;
1556 public:
1557   Parker*     parker() { return _parker; }
1558 
1559   // Biased locking support
1560 private:
1561   GrowableArray<MonitorInfo*>* _cached_monitor_info;
1562 public:
1563   GrowableArray<MonitorInfo*>* cached_monitor_info() { return _cached_monitor_info; }
1564   void set_cached_monitor_info(GrowableArray<MonitorInfo*>* info) { _cached_monitor_info = info; }
1565 
1566   // clearing/querying jni attach status
1567   bool is_attaching() const { return _is_attaching; }
1568   void set_attached() { _is_attaching = false; OrderAccess::fence(); }
1569 private:
1570   // This field is used to determine if a thread has claimed
1571   // a par_id: it is -1 if the thread has not claimed a par_id;
1572   // otherwise its value is the par_id that has been claimed.
1573   int _claimed_par_id;
1574 public:
1575   int get_claimed_par_id() { return _claimed_par_id; }
1576   void set_claimed_par_id(int id) { _claimed_par_id = id;}
1577 };
1578 
1579 // Inline implementation of JavaThread::current
1580 inline JavaThread* JavaThread::current() {
1581   Thread* thread = ThreadLocalStorage::thread();
1582   assert(thread != NULL && thread->is_Java_thread(), "just checking");
1583   return (JavaThread*)thread;
1584 }
1585 
1586 inline CompilerThread* JavaThread::as_CompilerThread() {
1587   assert(is_Compiler_thread(), "just checking");
1588   return (CompilerThread*)this;
1589 }
1590 
1591 inline bool JavaThread::stack_yellow_zone_disabled() {
1592   return _stack_guard_state == stack_guard_yellow_disabled;
1593 }
1594 
1595 inline bool JavaThread::stack_yellow_zone_enabled() {
1596 #ifdef ASSERT
1597   if (os::uses_stack_guard_pages()) {
1598     assert(_stack_guard_state != stack_guard_unused, "guard pages must be in use");
1599   }
1600 #endif
1601     return _stack_guard_state == stack_guard_enabled;
1602 }
1603 
1604 inline size_t JavaThread::stack_available(address cur_sp) {
1605   // This code assumes java stacks grow down
1606   address low_addr; // Limit on the address for deepest stack depth
1607   if ( _stack_guard_state == stack_guard_unused) {
1608     low_addr =  stack_base() - stack_size();
1609   } else {
1610     low_addr = stack_yellow_zone_base();
1611   }
1612   return cur_sp > low_addr ? cur_sp - low_addr : 0;
1613 }
1614 
1615 // A JavaThread for low memory detection support
1616 class LowMemoryDetectorThread : public JavaThread {
1617   friend class VMStructs;
1618 public:
1619   LowMemoryDetectorThread(ThreadFunction entry_point) : JavaThread(entry_point) {};
1620 
1621   // Hide this thread from external view.
1622   bool is_hidden_from_external_view() const      { return true; }
1623 };
1624 
1625 // A thread used for Compilation.
1626 class CompilerThread : public JavaThread {
1627   friend class VMStructs;
1628  private:
1629   CompilerCounters* _counters;
1630 
1631   ciEnv*        _env;
1632   CompileLog*   _log;
1633   CompileTask*  _task;
1634   CompileQueue* _queue;
1635   BufferBlob*   _buffer_blob;
1636 
1637  public:
1638 
1639   static CompilerThread* current();
1640 
1641   CompilerThread(CompileQueue* queue, CompilerCounters* counters);
1642 
1643   bool is_Compiler_thread() const                { return true; }
1644   // Hide this compiler thread from external view.
1645   bool is_hidden_from_external_view() const      { return true; }
1646 
1647   CompileQueue* queue()                          { return _queue; }
1648   CompilerCounters* counters()                   { return _counters; }
1649 
1650   // Get/set the thread's compilation environment.
1651   ciEnv*        env()                            { return _env; }
1652   void          set_env(ciEnv* env)              { _env = env; }
1653 
1654   BufferBlob*   get_buffer_blob()                { return _buffer_blob; }
1655   void          set_buffer_blob(BufferBlob* b)   { _buffer_blob = b; };
1656 
1657   // Get/set the thread's logging information
1658   CompileLog*   log()                            { return _log; }
1659   void          init_log(CompileLog* log) {
1660     // Set once, for good.
1661     assert(_log == NULL, "set only once");
1662     _log = log;
1663   }
1664 
1665 #ifndef PRODUCT
1666 private:
1667   IdealGraphPrinter *_ideal_graph_printer;
1668 public:
1669   IdealGraphPrinter *ideal_graph_printer()                       { return _ideal_graph_printer; }
1670   void set_ideal_graph_printer(IdealGraphPrinter *n)             { _ideal_graph_printer = n; }
1671 #endif
1672 
1673   // Get/set the thread's current task
1674   CompileTask*  task()                           { return _task; }
1675   void          set_task(CompileTask* task)      { _task = task; }
1676 };
1677 
1678 inline CompilerThread* CompilerThread::current() {
1679   return JavaThread::current()->as_CompilerThread();
1680 }
1681 
1682 
1683 // The active thread queue. It also keeps track of the current used
1684 // thread priorities.
1685 class Threads: AllStatic {
1686   friend class VMStructs;
1687  private:
1688   static JavaThread* _thread_list;
1689   static int         _number_of_threads;
1690   static int         _number_of_non_daemon_threads;
1691   static int         _return_code;
1692 
1693  public:
1694   // Thread management
1695   // force_daemon is a concession to JNI, where we may need to add a
1696   // thread to the thread list before allocating its thread object
1697   static void add(JavaThread* p, bool force_daemon = false);
1698   static void remove(JavaThread* p);
1699   static bool includes(JavaThread* p);
1700   static JavaThread* first()                     { return _thread_list; }
1701   static void threads_do(ThreadClosure* tc);
1702 
1703   // Initializes the vm and creates the vm thread
1704   static jint create_vm(JavaVMInitArgs* args, bool* canTryAgain);
1705   static void convert_vm_init_libraries_to_agents();
1706   static void create_vm_init_libraries();
1707   static void create_vm_init_agents();
1708   static void shutdown_vm_agents();
1709   static bool destroy_vm();
1710   // Supported VM versions via JNI
1711   // Includes JNI_VERSION_1_1
1712   static jboolean is_supported_jni_version_including_1_1(jint version);
1713   // Does not include JNI_VERSION_1_1
1714   static jboolean is_supported_jni_version(jint version);
1715 
1716   // Garbage collection
1717   static void follow_other_roots(void f(oop*));
1718 
1719   // Apply "f->do_oop" to all root oops in all threads.
1720   // This version may only be called by sequential code.
1721   static void oops_do(OopClosure* f, CodeBlobClosure* cf);
1722   // This version may be called by sequential or parallel code.
1723   static void possibly_parallel_oops_do(OopClosure* f, CodeBlobClosure* cf);
1724   // This creates a list of GCTasks, one per thread.
1725   static void create_thread_roots_tasks(GCTaskQueue* q);
1726   // This creates a list of GCTasks, one per thread, for marking objects.
1727   static void create_thread_roots_marking_tasks(GCTaskQueue* q);
1728 
1729   // Apply "f->do_oop" to roots in all threads that
1730   // are part of compiled frames
1731   static void compiled_frame_oops_do(OopClosure* f, CodeBlobClosure* cf);
1732 
1733   static void convert_hcode_pointers();
1734   static void restore_hcode_pointers();
1735 
1736   // Sweeper
1737   static void nmethods_do(CodeBlobClosure* cf);
1738 
1739   static void gc_epilogue();
1740   static void gc_prologue();
1741 
1742   // Verification
1743   static void verify();
1744   static void print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks);
1745   static void print(bool print_stacks, bool internal_format) {
1746     // this function is only used by debug.cpp
1747     print_on(tty, print_stacks, internal_format, false /* no concurrent lock printed */);
1748   }
1749   static void print_on_error(outputStream* st, Thread* current, char* buf, int buflen);
1750 
1751   // Get Java threads that are waiting to enter a monitor. If doLock
1752   // is true, then Threads_lock is grabbed as needed. Otherwise, the
1753   // VM needs to be at a safepoint.
1754   static GrowableArray<JavaThread*>* get_pending_threads(int count,
1755     address monitor, bool doLock);
1756 
1757   // Get owning Java thread from the monitor's owner field. If doLock
1758   // is true, then Threads_lock is grabbed as needed. Otherwise, the
1759   // VM needs to be at a safepoint.
1760   static JavaThread *owning_thread_from_monitor_owner(address owner,
1761     bool doLock);
1762 
1763   // Number of threads on the active threads list
1764   static int number_of_threads()                 { return _number_of_threads; }
1765   // Number of non-daemon threads on the active threads list
1766   static int number_of_non_daemon_threads()      { return _number_of_non_daemon_threads; }
1767 
1768   // Deoptimizes all frames tied to marked nmethods
1769   static void deoptimized_wrt_marked_nmethods();
1770 
1771 };
1772 
1773 
1774 // Thread iterator
1775 class ThreadClosure: public StackObj {
1776  public:
1777   virtual void do_thread(Thread* thread) = 0;
1778 };
1779 
1780 class SignalHandlerMark: public StackObj {
1781 private:
1782   Thread* _thread;
1783 public:
1784   SignalHandlerMark(Thread* t) {
1785     _thread = t;
1786     if (_thread) _thread->enter_signal_handler();
1787   }
1788   ~SignalHandlerMark() {
1789     if (_thread) _thread->leave_signal_handler();
1790     _thread = NULL;
1791   }
1792 };
1793 
1794 // ParkEvents are type-stable and immortal.
1795 //
1796 // Lifecycle: Once a ParkEvent is associated with a thread that ParkEvent remains
1797 // associated with the thread for the thread's entire lifetime - the relationship is
1798 // stable. A thread will be associated at most one ParkEvent.  When the thread
1799 // expires, the ParkEvent moves to the EventFreeList.  New threads attempt to allocate from
1800 // the EventFreeList before creating a new Event.  Type-stability frees us from
1801 // worrying about stale Event or Thread references in the objectMonitor subsystem.
1802 // (A reference to ParkEvent is always valid, even though the event may no longer be associated
1803 // with the desired or expected thread.  A key aspect of this design is that the callers of
1804 // park, unpark, etc must tolerate stale references and spurious wakeups).
1805 //
1806 // Only the "associated" thread can block (park) on the ParkEvent, although
1807 // any other thread can unpark a reachable parkevent.  Park() is allowed to
1808 // return spuriously.  In fact park-unpark a really just an optimization to
1809 // avoid unbounded spinning and surrender the CPU to be a polite system citizen.
1810 // A degenerate albeit "impolite" park-unpark implementation could simply return.
1811 // See http://blogs.sun.com/dave for more details.
1812 //
1813 // Eventually I'd like to eliminate Events and ObjectWaiters, both of which serve as
1814 // thread proxies, and simply make the THREAD structure type-stable and persistent.
1815 // Currently, we unpark events associated with threads, but ideally we'd just
1816 // unpark threads.
1817 //
1818 // The base-class, PlatformEvent, is platform-specific while the ParkEvent is
1819 // platform-independent.  PlatformEvent provides park(), unpark(), etc., and
1820 // is abstract -- that is, a PlatformEvent should never be instantiated except
1821 // as part of a ParkEvent.
1822 // Equivalently we could have defined a platform-independent base-class that
1823 // exported Allocate(), Release(), etc.  The platform-specific class would extend
1824 // that base-class, adding park(), unpark(), etc.
1825 //
1826 // A word of caution: The JVM uses 2 very similar constructs:
1827 // 1. ParkEvent are used for Java-level "monitor" synchronization.
1828 // 2. Parkers are used by JSR166-JUC park-unpark.
1829 //
1830 // We'll want to eventually merge these redundant facilities and use ParkEvent.
1831 
1832 
1833 class ParkEvent : public os::PlatformEvent {
1834   private:
1835     ParkEvent * FreeNext ;
1836 
1837     // Current association
1838     Thread * AssociatedWith ;
1839     intptr_t RawThreadIdentity ;        // LWPID etc
1840     volatile int Incarnation ;
1841 
1842     // diagnostic : keep track of last thread to wake this thread.
1843     // this is useful for construction of dependency graphs.
1844     void * LastWaker ;
1845 
1846   public:
1847     // MCS-CLH list linkage and Native Mutex/Monitor
1848     ParkEvent * volatile ListNext ;
1849     ParkEvent * volatile ListPrev ;
1850     volatile intptr_t OnList ;
1851     volatile int TState ;
1852     volatile int Notified ;             // for native monitor construct
1853     volatile int IsWaiting ;            // Enqueued on WaitSet
1854 
1855 
1856   private:
1857     static ParkEvent * volatile FreeList ;
1858     static volatile int ListLock ;
1859 
1860     // It's prudent to mark the dtor as "private"
1861     // ensuring that it's not visible outside the package.
1862     // Unfortunately gcc warns about such usage, so
1863     // we revert to the less desirable "protected" visibility.
1864     // The other compilers accept private dtors.
1865 
1866   protected:        // Ensure dtor is never invoked
1867     ~ParkEvent() { guarantee (0, "invariant") ; }
1868 
1869     ParkEvent() : PlatformEvent() {
1870        AssociatedWith = NULL ;
1871        FreeNext       = NULL ;
1872        ListNext       = NULL ;
1873        ListPrev       = NULL ;
1874        OnList         = 0 ;
1875        TState         = 0 ;
1876        Notified       = 0 ;
1877        IsWaiting      = 0 ;
1878     }
1879 
1880     // We use placement-new to force ParkEvent instances to be
1881     // aligned on 256-byte address boundaries.  This ensures that the least
1882     // significant byte of a ParkEvent address is always 0.
1883 
1884     void * operator new (size_t sz) ;
1885     void operator delete (void * a) ;
1886 
1887   public:
1888     static ParkEvent * Allocate (Thread * t) ;
1889     static void Release (ParkEvent * e) ;
1890 } ;
1891 
1892 #endif // SHARE_VM_RUNTIME_THREAD_HPP