1 /*
2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #ifndef SHARE_VM_RUNTIME_SAFEPOINT_HPP
26 #define SHARE_VM_RUNTIME_SAFEPOINT_HPP
27 
28 #include "asm/assembler.hpp"
29 #include "code/nmethod.hpp"
30 #include "memory/allocation.hpp"
31 #include "runtime/atomic.hpp"
32 #include "runtime/extendedPC.hpp"
33 #include "runtime/mutexLocker.hpp"
34 #include "runtime/os.hpp"
35 #include "utilities/ostream.hpp"
36 
37 //
38 // Safepoint synchronization
39 ////
40 // The VMThread or CMS_thread uses the SafepointSynchronize::begin/end
41 // methods to enter/exit a safepoint region. The begin method will roll
42 // all JavaThreads forward to a safepoint.
43 //
44 // JavaThreads must use the ThreadSafepointState abstraction (defined in
45 // thread.hpp) to indicate that that they are at a safepoint.
46 //
47 // The Mutex/Condition variable and ObjectLocker classes calls the enter/
48 // exit safepoint methods, when a thread is blocked/restarted. Hence, all mutex exter/
49 // exit points *must* be at a safepoint.
50 
51 
52 class ThreadSafepointState;
53 class SnippetCache;
54 class nmethod;
55 
56 //
57 // Implements roll-forward to safepoint (safepoint synchronization)
58 //
59 class SafepointSynchronize : AllStatic {
60  public:
61   enum SynchronizeState {
62       _not_synchronized = 0,                   // Threads not synchronized at a safepoint
63                                                // Keep this value 0. See the comment in do_call_back()
64       _synchronizing    = 1,                   // Synchronizing in progress
65       _synchronized     = 2                    // All Java threads are stopped at a safepoint. Only VM thread is running
66   };
67 
68   enum SafepointingThread {
69       _null_thread  = 0,
70       _vm_thread    = 1,
71       _other_thread = 2
72   };
73 
74   enum SafepointTimeoutReason {
75     _spinning_timeout = 0,
76     _blocking_timeout = 1
77   };
78 
79   // The enums are listed in the order of the tasks when done serially.
80   enum SafepointCleanupTasks {
81     SAFEPOINT_CLEANUP_DEFLATE_MONITORS,
82     SAFEPOINT_CLEANUP_UPDATE_INLINE_CACHES,
83     SAFEPOINT_CLEANUP_COMPILATION_POLICY,
84     SAFEPOINT_CLEANUP_SYMBOL_TABLE_REHASH,
85     SAFEPOINT_CLEANUP_STRING_TABLE_REHASH,
86     SAFEPOINT_CLEANUP_CLD_PURGE,
87     SAFEPOINT_CLEANUP_SYSTEM_DICTIONARY_RESIZE,
88     // Leave this one last.
89     SAFEPOINT_CLEANUP_NUM_TASKS
90   };
91 
92   typedef struct {
93     float  _time_stamp;                        // record when the current safepoint occurs in seconds
94     int    _vmop_type;                         // type of VM operation triggers the safepoint
95     int    _nof_total_threads;                 // total number of Java threads
96     int    _nof_initial_running_threads;       // total number of initially seen running threads
97     int    _nof_threads_wait_to_block;         // total number of threads waiting for to block
98     int    _nof_threads_hit_page_trap;         // total number of threads hitting the page trap
99     jlong  _time_to_spin;                      // total time in millis spent in spinning
100     jlong  _time_to_wait_to_block;             // total time in millis spent in waiting for to block
101     jlong  _time_to_do_cleanups;               // total time in millis spent in performing cleanups
102     jlong  _time_to_sync;                      // total time in millis spent in getting to _synchronized
103     jlong  _time_to_exec_vmop;                 // total time in millis spent in vm operation itself
104   } SafepointStats;
105 
106  private:
107   static volatile SynchronizeState _state;     // Threads might read this flag directly, without acquiring the Threads_lock
108   static volatile int _waiting_to_block;       // number of threads we are waiting for to block
109   static int _current_jni_active_count;        // Counts the number of active critical natives during the safepoint
110   static int _defer_thr_suspend_loop_count;    // Iterations before blocking VM threads
111 
112   // This counter is used for fast versions of jni_Get<Primitive>Field.
113   // An even value means there is no ongoing safepoint operations.
114   // The counter is incremented ONLY at the beginning and end of each
115   // safepoint. The fact that Threads_lock is held throughout each pair of
116   // increments (at the beginning and end of each safepoint) guarantees
117   // race freedom.
118 public:
119   static volatile int _safepoint_counter;
120 private:
121   static long       _end_of_last_safepoint;     // Time of last safepoint in milliseconds
122 
123   // Statistics
124   static jlong            _safepoint_begin_time;     // time when safepoint begins
125   static SafepointStats*  _safepoint_stats;          // array of SafepointStats struct
126   static int              _cur_stat_index;           // current index to the above array
127   static julong           _safepoint_reasons[];      // safepoint count for each VM op
128   static julong           _coalesced_vmop_count;     // coalesced vmop count
129   static jlong            _max_sync_time;            // maximum sync time in nanos
130   static jlong            _max_vmop_time;            // maximum vm operation time in nanos
131   static float            _ts_of_current_safepoint;  // time stamp of current safepoint in seconds
132 
133   static void begin_statistics(int nof_threads, int nof_running);
134   static void update_statistics_on_spin_end();
135   static void update_statistics_on_sync_end(jlong end_time);
136   static void update_statistics_on_cleanup_end(jlong end_time);
137   static void end_statistics(jlong end_time);
138   static void print_statistics();
inc_page_trap_count()139   inline static void inc_page_trap_count() {
140     Atomic::inc(&_safepoint_stats[_cur_stat_index]._nof_threads_hit_page_trap);
141   }
142 
143   // For debug long safepoint
144   static void print_safepoint_timeout(SafepointTimeoutReason timeout_reason);
145 
146 public:
147 
148   // Main entry points
149 
150   // Roll all threads forward to safepoint. Must be called by the
151   // VMThread or CMS_thread.
152   static void begin();
153   static void end();                    // Start all suspended threads again...
154 
155   static bool safepoint_safe(JavaThread *thread, JavaThreadState state);
156 
157   static void check_for_lazy_critical_native(JavaThread *thread, JavaThreadState state);
158 
159   // Query
is_at_safepoint()160   inline static bool is_at_safepoint()   { return _state == _synchronized;  }
is_synchronizing()161   inline static bool is_synchronizing()  { return _state == _synchronizing;  }
safepoint_counter()162   inline static int safepoint_counter()  { return _safepoint_counter; }
163 
increment_jni_active_count()164   inline static void increment_jni_active_count() {
165     assert_locked_or_safepoint(Safepoint_lock);
166     _current_jni_active_count++;
167   }
168 
169 private:
do_call_back()170   inline static bool do_call_back() {
171     return (_state != _not_synchronized);
172   }
173 
174   // Called when a thread voluntarily blocks
175   static void   block(JavaThread *thread);
176 
177   friend class SafepointMechanism;
178 
179 public:
signal_thread_at_safepoint()180   static void   signal_thread_at_safepoint()              { _waiting_to_block--; }
181 
182   // Exception handling for page polling
183   static void handle_polling_page_exception(JavaThread *thread);
184 
185   // VM Thread interface for determining safepoint rate
last_non_safepoint_interval()186   static long last_non_safepoint_interval() {
187     return os::javaTimeMillis() - _end_of_last_safepoint;
188   }
end_of_last_safepoint()189   static long end_of_last_safepoint() {
190     return _end_of_last_safepoint;
191   }
192   static bool is_cleanup_needed();
193   static void do_cleanup_tasks();
194 
195   static void deferred_initialize_stat();
196   static void print_stat_on_exit();
inc_vmop_coalesced_count()197   inline static void inc_vmop_coalesced_count() { _coalesced_vmop_count++; }
198 
set_is_at_safepoint()199   static void set_is_at_safepoint()                        { _state = _synchronized; }
set_is_not_at_safepoint()200   static void set_is_not_at_safepoint()                    { _state = _not_synchronized; }
201 
202   // Assembly support
address_of_state()203   static address address_of_state()                        { return (address)&_state; }
204 
safepoint_counter_addr()205   static address safepoint_counter_addr()                  { return (address)&_safepoint_counter; }
206 
207   // This method is only used for -Xconcurrentio support.
set_defer_thr_suspend_loop_count()208   static void set_defer_thr_suspend_loop_count() {
209     _defer_thr_suspend_loop_count = 1;
210   }
211 };
212 
213 // Some helper assert macros for safepoint checks.
214 
215 #define assert_at_safepoint()                                           \
216   assert(SafepointSynchronize::is_at_safepoint(), "should be at a safepoint")
217 
218 #define assert_at_safepoint_msg(...)                                    \
219   assert(SafepointSynchronize::is_at_safepoint(), __VA_ARGS__)
220 
221 #define assert_not_at_safepoint()                                       \
222   assert(!SafepointSynchronize::is_at_safepoint(), "should not be at a safepoint")
223 
224 #define assert_not_at_safepoint_msg(...)                                \
225   assert(!SafepointSynchronize::is_at_safepoint(), __VA_ARGS__)
226 
227 // State class for a thread suspended at a safepoint
228 class ThreadSafepointState: public CHeapObj<mtThread> {
229  public:
230   // These states are maintained by VM thread while threads are being brought
231   // to a safepoint.  After SafepointSynchronize::end(), they are reset to
232   // _running.
233   enum suspend_type {
234     _running                =  0, // Thread state not yet determined (i.e., not at a safepoint yet)
235     _at_safepoint           =  1, // Thread at a safepoint (f.ex., when blocked on a lock)
236     _call_back              =  2  // Keep executing and wait for callback (if thread is in interpreted or vm)
237   };
238  private:
239   volatile bool _at_poll_safepoint;  // At polling page safepoint (NOT a poll return safepoint)
240   // Thread has called back the safepoint code (for debugging)
241   bool                           _has_called_back;
242 
243   JavaThread *                   _thread;
244   volatile suspend_type          _type;
245   JavaThreadState                _orig_thread_state;
246 
247 
248  public:
249   ThreadSafepointState(JavaThread *thread);
250 
251   // examine/roll-forward/restart
252   void examine_state_of_thread();
253   void roll_forward(suspend_type type);
254   void restart();
255 
256   // Query
thread() const257   JavaThread*  thread() const         { return _thread; }
type() const258   suspend_type type() const           { return _type; }
is_running() const259   bool         is_running() const     { return (_type==_running); }
orig_thread_state() const260   JavaThreadState orig_thread_state() const { return _orig_thread_state; }
261 
262   // Support for safepoint timeout (debugging)
has_called_back() const263   bool has_called_back() const                   { return _has_called_back; }
set_has_called_back(bool val)264   void set_has_called_back(bool val)             { _has_called_back = val; }
is_at_poll_safepoint()265   bool              is_at_poll_safepoint() { return _at_poll_safepoint; }
set_at_poll_safepoint(bool val)266   void              set_at_poll_safepoint(bool val) { _at_poll_safepoint = val; }
267 
268   void handle_polling_page_exception();
269 
270   // debugging
271   void print_on(outputStream* st) const;
print() const272   void print() const                        { print_on(tty); }
273 
274   // Initialize
275   static void create(JavaThread *thread);
276   static void destroy(JavaThread *thread);
277 };
278 
279 
280 
281 #endif // SHARE_VM_RUNTIME_SAFEPOINT_HPP
282