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/classLoaderData.hpp"
  27 #include "gc/g1/concurrentMarkThread.inline.hpp"
  28 #include "gc/g1/g1CollectedHeap.inline.hpp"
  29 #include "gc/g1/g1CollectorPolicy.hpp"
  30 #include "gc/g1/g1MMUTracker.hpp"
  31 #include "gc/g1/suspendibleThreadSet.hpp"
  32 #include "gc/g1/vm_operations_g1.hpp"
  33 #include "gc/shared/gcId.hpp"
  34 #include "gc/shared/gcTrace.hpp"
  35 #include "gc/shared/gcTraceTime.inline.hpp"
  36 #include "logging/log.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "runtime/vmThread.hpp"
  39 
  40 // ======= Concurrent Mark Thread ========
  41 
  42 // The CM thread is created when the G1 garbage collector is used
  43 
  44 SurrogateLockerThread*
  45      ConcurrentMarkThread::_slt = NULL;
  46 
  47 ConcurrentMarkThread::ConcurrentMarkThread(G1ConcurrentMark* cm) :
  48   ConcurrentGCThread(),
  49   _cm(cm),
  50   _state(Idle),
  51   _vtime_accum(0.0),
  52   _vtime_mark_accum(0.0) {
  53 
  54   set_name("G1 Main Marker");
  55   create_and_start();
  56 }
  57 
  58 class CMCheckpointRootsFinalClosure: public VoidClosure {
  59 
  60   G1ConcurrentMark* _cm;
  61 public:
  62 
  63   CMCheckpointRootsFinalClosure(G1ConcurrentMark* cm) :
  64     _cm(cm) {}
  65 
  66   void do_void(){
  67     _cm->checkpointRootsFinal(false); // !clear_all_soft_refs
  68   }
  69 };
  70 
  71 class CMCleanUp: public VoidClosure {
  72   G1ConcurrentMark* _cm;
  73 public:
  74 
  75   CMCleanUp(G1ConcurrentMark* cm) :
  76     _cm(cm) {}
  77 
  78   void do_void(){
  79     _cm->cleanup();
  80   }
  81 };
  82 
  83 // Marking pauses can be scheduled flexibly, so we might delay marking to meet MMU.
  84 void ConcurrentMarkThread::delay_to_keep_mmu(G1CollectorPolicy* g1_policy, bool remark) {
  85   if (g1_policy->adaptive_young_list_length()) {
  86     double now = os::elapsedTime();
  87     double prediction_ms = remark ? g1_policy->predict_remark_time_ms()
  88                                   : g1_policy->predict_cleanup_time_ms();
  89     G1MMUTracker *mmu_tracker = g1_policy->mmu_tracker();
  90     jlong sleep_time_ms = mmu_tracker->when_ms(now, prediction_ms);
  91     os::sleep(this, sleep_time_ms, false);
  92   }
  93 }
  94 
  95 class G1ConcPhaseTimer : public GCTraceConcTimeImpl<LogLevel::Info, LogTag::_gc, LogTag::_marking> {
  96   G1ConcurrentMark* _cm;
  97 
  98  public:
  99   G1ConcPhaseTimer(G1ConcurrentMark* cm, const char* title) :
 100      GCTraceConcTimeImpl<LogLevel::Info,  LogTag::_gc, LogTag::_marking>(title),
 101      _cm(cm) {
 102     _cm->register_concurrent_phase_start(title);
 103   }
 104 
 105   ~G1ConcPhaseTimer() {
 106     _cm->register_concurrent_phase_end();
 107   }
 108 };
 109 
 110 void ConcurrentMarkThread::run() {
 111   initialize_in_thread();
 112   wait_for_universe_init();
 113 
 114   run_service();
 115 
 116   terminate();
 117 }
 118 
 119 void ConcurrentMarkThread::run_service() {
 120   _vtime_start = os::elapsedVTime();
 121 
 122   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 123   G1CollectorPolicy* g1_policy = g1h->g1_policy();
 124 
 125   while (!_should_terminate) {
 126     // wait until started is set.
 127     sleepBeforeNextCycle();
 128     if (_should_terminate) {
 129       _cm->root_regions()->cancel_scan();
 130       break;
 131     }
 132 
 133     assert(GCId::current() != GCId::undefined(), "GC id should have been set up by the initial mark GC.");
 134     {
 135       ResourceMark rm;
 136       HandleMark   hm;
 137       double cycle_start = os::elapsedVTime();
 138 
 139       {
 140         G1ConcPhaseTimer t(_cm, "Concurrent Clear Claimed Marks");
 141         ClassLoaderDataGraph::clear_claimed_marks();
 142       }
 143 
 144       // We have to ensure that we finish scanning the root regions
 145       // before the next GC takes place. To ensure this we have to
 146       // make sure that we do not join the STS until the root regions
 147       // have been scanned. If we did then it's possible that a
 148       // subsequent GC could block us from joining the STS and proceed
 149       // without the root regions have been scanned which would be a
 150       // correctness issue.
 151 
 152       {
 153         G1ConcPhaseTimer t(_cm, "Concurrent Scan Root Regions");
 154         _cm->scan_root_regions();
 155       }
 156 
 157       // It would be nice to use the GCTraceConcTime class here but
 158       // the "end" logging is inside the loop and not at the end of
 159       // a scope. Mimicking the same log output as GCTraceConcTime instead.
 160       jlong mark_start = os::elapsed_counter();
 161       log_info(gc, marking)("Concurrent Mark (%.3fs)", TimeHelper::counter_to_seconds(mark_start));
 162 
 163       int iter = 0;
 164       do {
 165         iter++;
 166         if (!cm()->has_aborted()) {
 167           G1ConcPhaseTimer t(_cm, "Concurrent Mark From Roots");
 168           _cm->mark_from_roots();
 169         }
 170 
 171         double mark_end_time = os::elapsedVTime();
 172         jlong mark_end = os::elapsed_counter();
 173         _vtime_mark_accum += (mark_end_time - cycle_start);
 174         if (!cm()->has_aborted()) {
 175           delay_to_keep_mmu(g1_policy, true /* remark */);
 176           log_info(gc, marking)("Concurrent Mark (%.3fs, %.3fs) %.3fms",
 177                                 TimeHelper::counter_to_seconds(mark_start),
 178                                 TimeHelper::counter_to_seconds(mark_end),
 179                                 TimeHelper::counter_to_millis(mark_end - mark_start));
 180 
 181           CMCheckpointRootsFinalClosure final_cl(_cm);
 182           VM_CGC_Operation op(&final_cl, "Pause Remark", true /* needs_pll */);
 183           VMThread::execute(&op);
 184         }
 185         if (cm()->restart_for_overflow()) {
 186           log_debug(gc, marking)("Restarting Concurrent Marking because of Mark Stack Overflow in Remark (Iteration #%d).", iter);
 187           log_info(gc, marking)("Concurrent Mark Restart due to overflow");
 188         }
 189       } while (cm()->restart_for_overflow());
 190 
 191       double end_time = os::elapsedVTime();
 192       // Update the total virtual time before doing this, since it will try
 193       // to measure it to get the vtime for this marking.  We purposely
 194       // neglect the presumably-short "completeCleanup" phase here.
 195       _vtime_accum = (end_time - _vtime_start);
 196 
 197       if (!cm()->has_aborted()) {
 198         delay_to_keep_mmu(g1_policy, false /* cleanup */);
 199 
 200         CMCleanUp cl_cl(_cm);
 201         VM_CGC_Operation op(&cl_cl, "Pause Cleanup", false /* needs_pll */);
 202         VMThread::execute(&op);
 203       } else {
 204         // We don't want to update the marking status if a GC pause
 205         // is already underway.
 206         SuspendibleThreadSetJoiner sts_join;
 207         g1h->collector_state()->set_mark_in_progress(false);
 208       }
 209 
 210       // Check if cleanup set the free_regions_coming flag. If it
 211       // hasn't, we can just skip the next step.
 212       if (g1h->free_regions_coming()) {
 213         // The following will finish freeing up any regions that we
 214         // found to be empty during cleanup. We'll do this part
 215         // without joining the suspendible set. If an evacuation pause
 216         // takes place, then we would carry on freeing regions in
 217         // case they are needed by the pause. If a Full GC takes
 218         // place, it would wait for us to process the regions
 219         // reclaimed by cleanup.
 220 
 221         G1ConcPhaseTimer t(_cm, "Concurrent Complete Cleanup");
 222 
 223         // Now do the concurrent cleanup operation.
 224         _cm->complete_cleanup();
 225 
 226         // Notify anyone who's waiting that there are no more free
 227         // regions coming. We have to do this before we join the STS
 228         // (in fact, we should not attempt to join the STS in the
 229         // interval between finishing the cleanup pause and clearing
 230         // the free_regions_coming flag) otherwise we might deadlock:
 231         // a GC worker could be blocked waiting for the notification
 232         // whereas this thread will be blocked for the pause to finish
 233         // while it's trying to join the STS, which is conditional on
 234         // the GC workers finishing.
 235         g1h->reset_free_regions_coming();
 236       }
 237       guarantee(cm()->cleanup_list_is_empty(),
 238                 "at this point there should be no regions on the cleanup list");
 239 
 240       // There is a tricky race before recording that the concurrent
 241       // cleanup has completed and a potential Full GC starting around
 242       // the same time. We want to make sure that the Full GC calls
 243       // abort() on concurrent mark after
 244       // record_concurrent_mark_cleanup_completed(), since abort() is
 245       // the method that will reset the concurrent mark state. If we
 246       // end up calling record_concurrent_mark_cleanup_completed()
 247       // after abort() then we might incorrectly undo some of the work
 248       // abort() did. Checking the has_aborted() flag after joining
 249       // the STS allows the correct ordering of the two methods. There
 250       // are two scenarios:
 251       //
 252       // a) If we reach here before the Full GC, the fact that we have
 253       // joined the STS means that the Full GC cannot start until we
 254       // leave the STS, so record_concurrent_mark_cleanup_completed()
 255       // will complete before abort() is called.
 256       //
 257       // b) If we reach here during the Full GC, we'll be held up from
 258       // joining the STS until the Full GC is done, which means that
 259       // abort() will have completed and has_aborted() will return
 260       // true to prevent us from calling
 261       // record_concurrent_mark_cleanup_completed() (and, in fact, it's
 262       // not needed any more as the concurrent mark state has been
 263       // already reset).
 264       {
 265         SuspendibleThreadSetJoiner sts_join;
 266         if (!cm()->has_aborted()) {
 267           g1_policy->record_concurrent_mark_cleanup_completed();
 268         } else {
 269           log_info(gc, marking)("Concurrent Mark Abort");
 270         }
 271       }
 272 
 273       // We now want to allow clearing of the marking bitmap to be
 274       // suspended by a collection pause.
 275       // We may have aborted just before the remark. Do not bother clearing the
 276       // bitmap then, as it has been done during mark abort.
 277       if (!cm()->has_aborted()) {
 278         G1ConcPhaseTimer t(_cm, "Concurrent Cleanup for Next Mark");
 279         _cm->cleanup_for_next_mark();
 280       } else {
 281         assert(!G1VerifyBitmaps || _cm->nextMarkBitmapIsClear(), "Next mark bitmap must be clear");
 282       }
 283     }
 284 
 285     // Update the number of full collections that have been
 286     // completed. This will also notify the FullGCCount_lock in case a
 287     // Java thread is waiting for a full GC to happen (e.g., it
 288     // called System.gc() with +ExplicitGCInvokesConcurrent).
 289     {
 290       SuspendibleThreadSetJoiner sts_join;
 291       g1h->increment_old_marking_cycles_completed(true /* concurrent */);
 292       g1h->register_concurrent_cycle_end();
 293     }
 294   }
 295 }
 296 
 297 void ConcurrentMarkThread::stop() {
 298   {
 299     MutexLockerEx ml(Terminator_lock);
 300     _should_terminate = true;
 301   }
 302 
 303   stop_service();
 304 
 305   {
 306     MutexLockerEx ml(Terminator_lock);
 307     while (!_has_terminated) {
 308       Terminator_lock->wait();
 309     }
 310   }
 311 }
 312 
 313 void ConcurrentMarkThread::stop_service() {
 314   MutexLockerEx ml(CGC_lock, Mutex::_no_safepoint_check_flag);
 315   CGC_lock->notify_all();
 316 }
 317 
 318 void ConcurrentMarkThread::sleepBeforeNextCycle() {
 319   // We join here because we don't want to do the "shouldConcurrentMark()"
 320   // below while the world is otherwise stopped.
 321   assert(!in_progress(), "should have been cleared");
 322 
 323   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
 324   while (!started() && !_should_terminate) {
 325     CGC_lock->wait(Mutex::_no_safepoint_check_flag);
 326   }
 327 
 328   if (started()) {
 329     set_in_progress();
 330   }
 331 }
 332 
 333 // Note: As is the case with CMS - this method, although exported
 334 // by the ConcurrentMarkThread, which is a non-JavaThread, can only
 335 // be called by a JavaThread. Currently this is done at vm creation
 336 // time (post-vm-init) by the main/Primordial (Java)Thread.
 337 // XXX Consider changing this in the future to allow the CM thread
 338 // itself to create this thread?
 339 void ConcurrentMarkThread::makeSurrogateLockerThread(TRAPS) {
 340   assert(UseG1GC, "SLT thread needed only for concurrent GC");
 341   assert(THREAD->is_Java_thread(), "must be a Java thread");
 342   assert(_slt == NULL, "SLT already created");
 343   _slt = SurrogateLockerThread::make(THREAD);
 344 }