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