1 /*
   2  * Copyright (c) 2001, 2015, 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 bool ConcurrentMarkSweepThread::_should_terminate           = false;
  46 int  ConcurrentMarkSweepThread::_CMS_flag                   = CMS_nil;
  47 
  48 volatile jint ConcurrentMarkSweepThread::_pending_yields    = 0;
  49 
  50 SurrogateLockerThread* ConcurrentMarkSweepThread::_slt      = NULL;
  51 SurrogateLockerThread::SLT_msg_type
  52      ConcurrentMarkSweepThread::_sltBuffer = SurrogateLockerThread::empty;
  53 Monitor* ConcurrentMarkSweepThread::_sltMonitor             = NULL;
  54 
  55 ConcurrentMarkSweepThread::ConcurrentMarkSweepThread(CMSCollector* collector)
  56   : ConcurrentGCThread() {
  57   assert(UseConcMarkSweepGC,  "UseConcMarkSweepGC should be set");
  58   assert(_cmst == NULL, "CMS thread already created");
  59   _cmst = this;
  60   assert(_collector == NULL, "Collector already set");
  61   _collector = collector;
  62 
  63   set_name("CMS Main Thread");
  64 
  65   if (os::create_thread(this, os::cgc_thread)) {
  66     // An old comment here said: "Priority should be just less
  67     // than that of VMThread".  Since the VMThread runs at
  68     // NearMaxPriority, the old comment was inaccurate, but
  69     // changing the default priority to NearMaxPriority-1
  70     // could change current behavior, so the default of
  71     // NearMaxPriority stays in place.
  72     //
  73     // Note that there's a possibility of the VMThread
  74     // starving if UseCriticalCMSThreadPriority is on.
  75     // That won't happen on Solaris for various reasons,
  76     // but may well happen on non-Solaris platforms.
  77     int native_prio;
  78     if (UseCriticalCMSThreadPriority) {
  79       native_prio = os::java_to_os_priority[CriticalPriority];
  80     } else {
  81       native_prio = os::java_to_os_priority[NearMaxPriority];
  82     }
  83     os::set_native_priority(this, native_prio);
  84 
  85     if (!DisableStartThread) {
  86       os::start_thread(this);
  87     }
  88   }
  89   _sltMonitor = SLT_lock;
  90 }
  91 
  92 void ConcurrentMarkSweepThread::run() {
  93   assert(this == cmst(), "just checking");
  94 
  95   initialize_in_thread();
  96   // From this time Thread::current() should be working.
  97   assert(this == Thread::current(), "just checking");
  98   if (BindCMSThreadToCPU && !os::bind_to_processor(CPUForCMSThread)) {
  99     warning("Couldn't bind CMS thread to processor " UINTX_FORMAT, CPUForCMSThread);
 100   }
 101   // Wait until Universe::is_fully_initialized()
 102   {
 103     CMSLoopCountWarn loopX("CMS::run", "waiting for "
 104                            "Universe::is_fully_initialized()", 2);
 105     MutexLockerEx x(CGC_lock, true);
 106     set_CMS_flag(CMS_cms_wants_token);
 107     // Wait until Universe is initialized and all initialization is completed.
 108     while (!is_init_completed() && !Universe::is_fully_initialized() &&
 109            !_should_terminate) {
 110       CGC_lock->wait(true, 200);
 111       loopX.tick();
 112     }
 113     // Wait until the surrogate locker thread that will do
 114     // pending list locking on our behalf has been created.
 115     // We cannot start the SLT thread ourselves since we need
 116     // to be a JavaThread to do so.
 117     CMSLoopCountWarn loopY("CMS::run", "waiting for SLT installation", 2);
 118     while (_slt == NULL && !_should_terminate) {
 119       CGC_lock->wait(true, 200);
 120       loopY.tick();
 121     }
 122     clear_CMS_flag(CMS_cms_wants_token);
 123   }
 124 
 125   while (!_should_terminate) {
 126     sleepBeforeNextCycle();
 127     if (_should_terminate) break;
 128     GCIdMark gc_id_mark;
 129     GCCause::Cause cause = _collector->_full_gc_requested ?
 130       _collector->_full_gc_cause : GCCause::_cms_concurrent_mark;
 131     _collector->collect_in_background(cause);
 132   }
 133   assert(_should_terminate, "just checking");
 134   // Check that the state of any protocol for synchronization
 135   // between background (CMS) and foreground collector is "clean"
 136   // (i.e. will not potentially block the foreground collector,
 137   // requiring action by us).
 138   verify_ok_to_terminate();
 139   // Signal that it is terminated
 140   {
 141     MutexLockerEx mu(Terminator_lock,
 142                      Mutex::_no_safepoint_check_flag);
 143     assert(_cmst == this, "Weird!");
 144     _cmst = NULL;
 145     Terminator_lock->notify();
 146   }
 147 
 148   // Thread destructor usually does this..
 149   ThreadLocalStorage::set_thread(NULL);
 150 }
 151 
 152 #ifndef PRODUCT
 153 void ConcurrentMarkSweepThread::verify_ok_to_terminate() const {
 154   assert(!(CGC_lock->owned_by_self() || cms_thread_has_cms_token() ||
 155            cms_thread_wants_cms_token()),
 156          "Must renounce all worldly possessions and desires for nirvana");
 157   _collector->verify_ok_to_terminate();
 158 }
 159 #endif
 160 
 161 // create and start a new ConcurrentMarkSweep Thread for given CMS generation
 162 ConcurrentMarkSweepThread* ConcurrentMarkSweepThread::start(CMSCollector* collector) {
 163   if (!_should_terminate) {
 164     assert(cmst() == NULL, "start() called twice?");
 165     ConcurrentMarkSweepThread* th = new ConcurrentMarkSweepThread(collector);
 166     assert(cmst() == th, "Where did the just-created CMS thread go?");
 167     return th;
 168   }
 169   return NULL;
 170 }
 171 
 172 void ConcurrentMarkSweepThread::stop() {
 173   // it is ok to take late safepoints here, if needed
 174   {
 175     MutexLockerEx x(Terminator_lock);
 176     _should_terminate = true;
 177   }
 178   { // Now post a notify on CGC_lock so as to nudge
 179     // CMS thread(s) that might be slumbering in
 180     // sleepBeforeNextCycle.
 181     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
 182     CGC_lock->notify_all();
 183   }
 184   { // Now wait until (all) CMS thread(s) have exited
 185     MutexLockerEx x(Terminator_lock);
 186     while(cmst() != NULL) {
 187       Terminator_lock->wait();
 188     }
 189   }
 190 }
 191 
 192 void ConcurrentMarkSweepThread::threads_do(ThreadClosure* tc) {
 193   assert(tc != NULL, "Null ThreadClosure");
 194   if (_cmst != NULL) {
 195     tc->do_thread(_cmst);
 196   }
 197   assert(Universe::is_fully_initialized(),
 198          "Called too early, make sure heap is fully initialized");
 199   if (_collector != NULL) {
 200     AbstractWorkGang* gang = _collector->conc_workers();
 201     if (gang != NULL) {
 202       gang->threads_do(tc);
 203     }
 204   }
 205 }
 206 
 207 void ConcurrentMarkSweepThread::print_all_on(outputStream* st) {
 208   if (_cmst != NULL) {
 209     _cmst->print_on(st);
 210     st->cr();
 211   }
 212   if (_collector != NULL) {
 213     AbstractWorkGang* gang = _collector->conc_workers();
 214     if (gang != NULL) {
 215       gang->print_worker_threads_on(st);
 216     }
 217   }
 218 }
 219 
 220 void ConcurrentMarkSweepThread::synchronize(bool is_cms_thread) {
 221   assert(UseConcMarkSweepGC, "just checking");
 222 
 223   MutexLockerEx x(CGC_lock,
 224                   Mutex::_no_safepoint_check_flag);
 225   if (!is_cms_thread) {
 226     assert(Thread::current()->is_VM_thread(), "Not a VM thread");
 227     CMSSynchronousYieldRequest yr;
 228     while (CMS_flag_is_set(CMS_cms_has_token)) {
 229       // indicate that we want to get the token
 230       set_CMS_flag(CMS_vm_wants_token);
 231       CGC_lock->wait(true);
 232     }
 233     // claim the token and proceed
 234     clear_CMS_flag(CMS_vm_wants_token);
 235     set_CMS_flag(CMS_vm_has_token);
 236   } else {
 237     assert(Thread::current()->is_ConcurrentGC_thread(),
 238            "Not a CMS thread");
 239     // The following barrier assumes there's only one CMS thread.
 240     // This will need to be modified is there are more CMS threads than one.
 241     while (CMS_flag_is_set(CMS_vm_has_token | CMS_vm_wants_token)) {
 242       set_CMS_flag(CMS_cms_wants_token);
 243       CGC_lock->wait(true);
 244     }
 245     // claim the token
 246     clear_CMS_flag(CMS_cms_wants_token);
 247     set_CMS_flag(CMS_cms_has_token);
 248   }
 249 }
 250 
 251 void ConcurrentMarkSweepThread::desynchronize(bool is_cms_thread) {
 252   assert(UseConcMarkSweepGC, "just checking");
 253 
 254   MutexLockerEx x(CGC_lock,
 255                   Mutex::_no_safepoint_check_flag);
 256   if (!is_cms_thread) {
 257     assert(Thread::current()->is_VM_thread(), "Not a VM thread");
 258     assert(CMS_flag_is_set(CMS_vm_has_token), "just checking");
 259     clear_CMS_flag(CMS_vm_has_token);
 260     if (CMS_flag_is_set(CMS_cms_wants_token)) {
 261       // wake-up a waiting CMS thread
 262       CGC_lock->notify();
 263     }
 264     assert(!CMS_flag_is_set(CMS_vm_has_token | CMS_vm_wants_token),
 265            "Should have been cleared");
 266   } else {
 267     assert(Thread::current()->is_ConcurrentGC_thread(),
 268            "Not a CMS thread");
 269     assert(CMS_flag_is_set(CMS_cms_has_token), "just checking");
 270     clear_CMS_flag(CMS_cms_has_token);
 271     if (CMS_flag_is_set(CMS_vm_wants_token)) {
 272       // wake-up a waiting VM thread
 273       CGC_lock->notify();
 274     }
 275     assert(!CMS_flag_is_set(CMS_cms_has_token | CMS_cms_wants_token),
 276            "Should have been cleared");
 277   }
 278 }
 279 
 280 // Wait until any cms_lock event
 281 void ConcurrentMarkSweepThread::wait_on_cms_lock(long t_millis) {
 282   MutexLockerEx x(CGC_lock,
 283                   Mutex::_no_safepoint_check_flag);
 284   if (_should_terminate || _collector->_full_gc_requested) {
 285     return;
 286   }
 287   set_CMS_flag(CMS_cms_wants_token);   // to provoke notifies
 288   CGC_lock->wait(Mutex::_no_safepoint_check_flag, t_millis);
 289   clear_CMS_flag(CMS_cms_wants_token);
 290   assert(!CMS_flag_is_set(CMS_cms_has_token | CMS_cms_wants_token),
 291          "Should not be set");
 292 }
 293 
 294 // Wait until the next synchronous GC, a concurrent full gc request,
 295 // or a timeout, whichever is earlier.
 296 void ConcurrentMarkSweepThread::wait_on_cms_lock_for_scavenge(long t_millis) {
 297   // Wait time in millis or 0 value representing infinite wait for a scavenge
 298   assert(t_millis >= 0, "Wait time for scavenge should be 0 or positive");
 299 
 300   GenCollectedHeap* gch = GenCollectedHeap::heap();
 301   double start_time_secs = os::elapsedTime();
 302   double end_time_secs = start_time_secs + (t_millis / ((double) MILLIUNITS));
 303 
 304   // Total collections count before waiting loop
 305   unsigned int before_count;
 306   {
 307     MutexLockerEx hl(Heap_lock, Mutex::_no_safepoint_check_flag);
 308     before_count = gch->total_collections();
 309   }
 310 
 311   unsigned int loop_count = 0;
 312 
 313   while(!_should_terminate) {
 314     double now_time = os::elapsedTime();
 315     long wait_time_millis;
 316 
 317     if(t_millis != 0) {
 318       // New wait limit
 319       wait_time_millis = (long) ((end_time_secs - now_time) * MILLIUNITS);
 320       if(wait_time_millis <= 0) {
 321         // Wait time is over
 322         break;
 323       }
 324     } else {
 325       // No wait limit, wait if necessary forever
 326       wait_time_millis = 0;
 327     }
 328 
 329     // Wait until the next event or the remaining timeout
 330     {
 331       MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
 332 
 333       if (_should_terminate || _collector->_full_gc_requested) {
 334         return;
 335       }
 336       set_CMS_flag(CMS_cms_wants_token);   // to provoke notifies
 337       assert(t_millis == 0 || wait_time_millis > 0, "Sanity");
 338       CGC_lock->wait(Mutex::_no_safepoint_check_flag, wait_time_millis);
 339       clear_CMS_flag(CMS_cms_wants_token);
 340       assert(!CMS_flag_is_set(CMS_cms_has_token | CMS_cms_wants_token),
 341              "Should not be set");
 342     }
 343 
 344     // Extra wait time check before entering the heap lock to get the collection count
 345     if(t_millis != 0 && os::elapsedTime() >= end_time_secs) {
 346       // Wait time is over
 347       break;
 348     }
 349 
 350     // Total collections count after the event
 351     unsigned int after_count;
 352     {
 353       MutexLockerEx hl(Heap_lock, Mutex::_no_safepoint_check_flag);
 354       after_count = gch->total_collections();
 355     }
 356 
 357     if(before_count != after_count) {
 358       // There was a collection - success
 359       break;
 360     }
 361 
 362     // Too many loops warning
 363     if(++loop_count == 0) {
 364       warning("wait_on_cms_lock_for_scavenge() has looped %u times", loop_count - 1);
 365     }
 366   }
 367 }
 368 
 369 void ConcurrentMarkSweepThread::sleepBeforeNextCycle() {
 370   while (!_should_terminate) {
 371     if(CMSWaitDuration >= 0) {
 372       // Wait until the next synchronous GC, a concurrent full gc
 373       // request or a timeout, whichever is earlier.
 374       wait_on_cms_lock_for_scavenge(CMSWaitDuration);
 375     } else {
 376       // Wait until any cms_lock event or check interval not to call shouldConcurrentCollect permanently
 377       wait_on_cms_lock(CMSCheckInterval);
 378     }
 379     // Check if we should start a CMS collection cycle
 380     if (_collector->shouldConcurrentCollect()) {
 381       return;
 382     }
 383     // .. collection criterion not yet met, let's go back
 384     // and wait some more
 385   }
 386 }
 387 
 388 // Note: this method, although exported by the ConcurrentMarkSweepThread,
 389 // which is a non-JavaThread, can only be called by a JavaThread.
 390 // Currently this is done at vm creation time (post-vm-init) by the
 391 // main/Primordial (Java)Thread.
 392 // XXX Consider changing this in the future to allow the CMS thread
 393 // itself to create this thread?
 394 void ConcurrentMarkSweepThread::makeSurrogateLockerThread(TRAPS) {
 395   assert(UseConcMarkSweepGC, "SLT thread needed only for CMS GC");
 396   assert(_slt == NULL, "SLT already created");
 397   _slt = SurrogateLockerThread::make(THREAD);
 398 }