1 /*
2  * Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "classfile/systemDictionary.hpp"
27 #include "gc/cms/cmsHeap.hpp"
28 #include "gc/cms/concurrentMarkSweepGeneration.inline.hpp"
29 #include "gc/cms/concurrentMarkSweepThread.hpp"
30 #include "gc/shared/gcId.hpp"
31 #include "oops/oop.inline.hpp"
32 #include "runtime/init.hpp"
33 #include "runtime/java.hpp"
34 #include "runtime/javaCalls.hpp"
35 #include "runtime/mutexLocker.hpp"
36 #include "runtime/os.hpp"
37 #include "runtime/vmThread.hpp"
38 
39 // ======= Concurrent Mark Sweep Thread ========
40 
41 ConcurrentMarkSweepThread* ConcurrentMarkSweepThread::_cmst = NULL;
42 CMSCollector* ConcurrentMarkSweepThread::_collector         = NULL;
43 int  ConcurrentMarkSweepThread::_CMS_flag                   = CMS_nil;
44 
45 volatile jint ConcurrentMarkSweepThread::_pending_yields    = 0;
46 
ConcurrentMarkSweepThread(CMSCollector * collector)47 ConcurrentMarkSweepThread::ConcurrentMarkSweepThread(CMSCollector* collector)
48   : ConcurrentGCThread() {
49   assert(UseConcMarkSweepGC,  "UseConcMarkSweepGC should be set");
50   assert(_cmst == NULL, "CMS thread already created");
51   _cmst = this;
52   assert(_collector == NULL, "Collector already set");
53   _collector = collector;
54 
55   set_name("CMS Main Thread");
56 
57   // An old comment here said: "Priority should be just less
58   // than that of VMThread".  Since the VMThread runs at
59   // NearMaxPriority, the old comment was inaccurate, but
60   // changing the default priority to NearMaxPriority-1
61   // could change current behavior, so the default of
62   // NearMaxPriority stays in place.
63   //
64   // Note that there's a possibility of the VMThread
65   // starving if UseCriticalCMSThreadPriority is on.
66   // That won't happen on Solaris for various reasons,
67   // but may well happen on non-Solaris platforms.
68   create_and_start(UseCriticalCMSThreadPriority ? CriticalPriority : NearMaxPriority);
69 }
70 
run_service()71 void ConcurrentMarkSweepThread::run_service() {
72   assert(this == cmst(), "just checking");
73 
74   if (BindCMSThreadToCPU && !os::bind_to_processor(CPUForCMSThread)) {
75     log_warning(gc)("Couldn't bind CMS thread to processor " UINTX_FORMAT, CPUForCMSThread);
76   }
77 
78   while (!should_terminate()) {
79     sleepBeforeNextCycle();
80     if (should_terminate()) break;
81     GCIdMark gc_id_mark;
82     GCCause::Cause cause = _collector->_full_gc_requested ?
83       _collector->_full_gc_cause : GCCause::_cms_concurrent_mark;
84     _collector->collect_in_background(cause);
85   }
86 
87   // Check that the state of any protocol for synchronization
88   // between background (CMS) and foreground collector is "clean"
89   // (i.e. will not potentially block the foreground collector,
90   // requiring action by us).
91   verify_ok_to_terminate();
92 }
93 
94 #ifndef PRODUCT
verify_ok_to_terminate() const95 void ConcurrentMarkSweepThread::verify_ok_to_terminate() const {
96   assert(!(CGC_lock->owned_by_self() || cms_thread_has_cms_token() ||
97            cms_thread_wants_cms_token()),
98          "Must renounce all worldly possessions and desires for nirvana");
99   _collector->verify_ok_to_terminate();
100 }
101 #endif
102 
103 // create and start a new ConcurrentMarkSweep Thread for given CMS generation
start(CMSCollector * collector)104 ConcurrentMarkSweepThread* ConcurrentMarkSweepThread::start(CMSCollector* collector) {
105   guarantee(_cmst == NULL, "start() called twice!");
106   ConcurrentMarkSweepThread* th = new ConcurrentMarkSweepThread(collector);
107   assert(_cmst == th, "Where did the just-created CMS thread go?");
108   return th;
109 }
110 
stop_service()111 void ConcurrentMarkSweepThread::stop_service() {
112   // Now post a notify on CGC_lock so as to nudge
113   // CMS thread(s) that might be slumbering in
114   // sleepBeforeNextCycle.
115   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
116   CGC_lock->notify_all();
117 }
118 
threads_do(ThreadClosure * tc)119 void ConcurrentMarkSweepThread::threads_do(ThreadClosure* tc) {
120   assert(tc != NULL, "Null ThreadClosure");
121   if (cmst() != NULL && !cmst()->has_terminated()) {
122     tc->do_thread(cmst());
123   }
124   assert(Universe::is_fully_initialized(),
125          "Called too early, make sure heap is fully initialized");
126   if (_collector != NULL) {
127     AbstractWorkGang* gang = _collector->conc_workers();
128     if (gang != NULL) {
129       gang->threads_do(tc);
130     }
131   }
132 }
133 
print_all_on(outputStream * st)134 void ConcurrentMarkSweepThread::print_all_on(outputStream* st) {
135   if (cmst() != NULL && !cmst()->has_terminated()) {
136     cmst()->print_on(st);
137     st->cr();
138   }
139   if (_collector != NULL) {
140     AbstractWorkGang* gang = _collector->conc_workers();
141     if (gang != NULL) {
142       gang->print_worker_threads_on(st);
143     }
144   }
145 }
146 
synchronize(bool is_cms_thread)147 void ConcurrentMarkSweepThread::synchronize(bool is_cms_thread) {
148   assert(UseConcMarkSweepGC, "just checking");
149 
150   MutexLockerEx x(CGC_lock,
151                   Mutex::_no_safepoint_check_flag);
152   if (!is_cms_thread) {
153     assert(Thread::current()->is_VM_thread(), "Not a VM thread");
154     CMSSynchronousYieldRequest yr;
155     while (CMS_flag_is_set(CMS_cms_has_token)) {
156       // indicate that we want to get the token
157       set_CMS_flag(CMS_vm_wants_token);
158       CGC_lock->wait(true);
159     }
160     // claim the token and proceed
161     clear_CMS_flag(CMS_vm_wants_token);
162     set_CMS_flag(CMS_vm_has_token);
163   } else {
164     assert(Thread::current()->is_ConcurrentGC_thread(),
165            "Not a CMS thread");
166     // The following barrier assumes there's only one CMS thread.
167     // This will need to be modified is there are more CMS threads than one.
168     while (CMS_flag_is_set(CMS_vm_has_token | CMS_vm_wants_token)) {
169       set_CMS_flag(CMS_cms_wants_token);
170       CGC_lock->wait(true);
171     }
172     // claim the token
173     clear_CMS_flag(CMS_cms_wants_token);
174     set_CMS_flag(CMS_cms_has_token);
175   }
176 }
177 
desynchronize(bool is_cms_thread)178 void ConcurrentMarkSweepThread::desynchronize(bool is_cms_thread) {
179   assert(UseConcMarkSweepGC, "just checking");
180 
181   MutexLockerEx x(CGC_lock,
182                   Mutex::_no_safepoint_check_flag);
183   if (!is_cms_thread) {
184     assert(Thread::current()->is_VM_thread(), "Not a VM thread");
185     assert(CMS_flag_is_set(CMS_vm_has_token), "just checking");
186     clear_CMS_flag(CMS_vm_has_token);
187     if (CMS_flag_is_set(CMS_cms_wants_token)) {
188       // wake-up a waiting CMS thread
189       CGC_lock->notify();
190     }
191     assert(!CMS_flag_is_set(CMS_vm_has_token | CMS_vm_wants_token),
192            "Should have been cleared");
193   } else {
194     assert(Thread::current()->is_ConcurrentGC_thread(),
195            "Not a CMS thread");
196     assert(CMS_flag_is_set(CMS_cms_has_token), "just checking");
197     clear_CMS_flag(CMS_cms_has_token);
198     if (CMS_flag_is_set(CMS_vm_wants_token)) {
199       // wake-up a waiting VM thread
200       CGC_lock->notify();
201     }
202     assert(!CMS_flag_is_set(CMS_cms_has_token | CMS_cms_wants_token),
203            "Should have been cleared");
204   }
205 }
206 
207 // Wait until any cms_lock event
wait_on_cms_lock(long t_millis)208 void ConcurrentMarkSweepThread::wait_on_cms_lock(long t_millis) {
209   MutexLockerEx x(CGC_lock,
210                   Mutex::_no_safepoint_check_flag);
211   if (should_terminate() || _collector->_full_gc_requested) {
212     return;
213   }
214   set_CMS_flag(CMS_cms_wants_token);   // to provoke notifies
215   CGC_lock->wait(Mutex::_no_safepoint_check_flag, t_millis);
216   clear_CMS_flag(CMS_cms_wants_token);
217   assert(!CMS_flag_is_set(CMS_cms_has_token | CMS_cms_wants_token),
218          "Should not be set");
219 }
220 
221 // Wait until the next synchronous GC, a concurrent full gc request,
222 // or a timeout, whichever is earlier.
wait_on_cms_lock_for_scavenge(long t_millis)223 void ConcurrentMarkSweepThread::wait_on_cms_lock_for_scavenge(long t_millis) {
224   // Wait time in millis or 0 value representing infinite wait for a scavenge
225   assert(t_millis >= 0, "Wait time for scavenge should be 0 or positive");
226 
227   CMSHeap* heap = CMSHeap::heap();
228   double start_time_secs = os::elapsedTime();
229   double end_time_secs = start_time_secs + (t_millis / ((double) MILLIUNITS));
230 
231   // Total collections count before waiting loop
232   unsigned int before_count;
233   {
234     MutexLockerEx hl(Heap_lock, Mutex::_no_safepoint_check_flag);
235     before_count = heap->total_collections();
236   }
237 
238   unsigned int loop_count = 0;
239 
240   while(!should_terminate()) {
241     double now_time = os::elapsedTime();
242     long wait_time_millis;
243 
244     if(t_millis != 0) {
245       // New wait limit
246       wait_time_millis = (long) ((end_time_secs - now_time) * MILLIUNITS);
247       if(wait_time_millis <= 0) {
248         // Wait time is over
249         break;
250       }
251     } else {
252       // No wait limit, wait if necessary forever
253       wait_time_millis = 0;
254     }
255 
256     // Wait until the next event or the remaining timeout
257     {
258       MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
259 
260       if (should_terminate() || _collector->_full_gc_requested) {
261         return;
262       }
263       set_CMS_flag(CMS_cms_wants_token);   // to provoke notifies
264       assert(t_millis == 0 || wait_time_millis > 0, "Sanity");
265       CGC_lock->wait(Mutex::_no_safepoint_check_flag, wait_time_millis);
266       clear_CMS_flag(CMS_cms_wants_token);
267       assert(!CMS_flag_is_set(CMS_cms_has_token | CMS_cms_wants_token),
268              "Should not be set");
269     }
270 
271     // Extra wait time check before entering the heap lock to get the collection count
272     if(t_millis != 0 && os::elapsedTime() >= end_time_secs) {
273       // Wait time is over
274       break;
275     }
276 
277     // Total collections count after the event
278     unsigned int after_count;
279     {
280       MutexLockerEx hl(Heap_lock, Mutex::_no_safepoint_check_flag);
281       after_count = heap->total_collections();
282     }
283 
284     if(before_count != after_count) {
285       // There was a collection - success
286       break;
287     }
288 
289     // Too many loops warning
290     if(++loop_count == 0) {
291       log_warning(gc)("wait_on_cms_lock_for_scavenge() has looped %u times", loop_count - 1);
292     }
293   }
294 }
295 
sleepBeforeNextCycle()296 void ConcurrentMarkSweepThread::sleepBeforeNextCycle() {
297   while (!should_terminate()) {
298     if(CMSWaitDuration >= 0) {
299       // Wait until the next synchronous GC, a concurrent full gc
300       // request or a timeout, whichever is earlier.
301       wait_on_cms_lock_for_scavenge(CMSWaitDuration);
302     } else {
303       // Wait until any cms_lock event or check interval not to call shouldConcurrentCollect permanently
304       wait_on_cms_lock(CMSCheckInterval);
305     }
306     // Check if we should start a CMS collection cycle
307     if (_collector->shouldConcurrentCollect()) {
308       return;
309     }
310     // .. collection criterion not yet met, let's go back
311     // and wait some more
312   }
313 }
314