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