1 /*
   2  * Copyright (c) 2001, 2018, 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/g1Analytics.hpp"
  29 #include "gc/g1/g1CollectedHeap.inline.hpp"
  30 #include "gc/g1/g1ConcurrentMark.inline.hpp"
  31 #include "gc/g1/g1MMUTracker.hpp"
  32 #include "gc/g1/g1Policy.hpp"
  33 #include "gc/g1/vm_operations_g1.hpp"
  34 #include "gc/shared/concurrentGCPhaseManager.hpp"
  35 #include "gc/shared/gcId.hpp"
  36 #include "gc/shared/gcTrace.hpp"
  37 #include "gc/shared/gcTraceTime.inline.hpp"
  38 #include "gc/shared/suspendibleThreadSet.hpp"
  39 #include "logging/log.hpp"
  40 #include "memory/resourceArea.hpp"
  41 #include "runtime/vmThread.hpp"
  42 #include "utilities/debug.hpp"
  43 
  44 // ======= Concurrent Mark Thread ========
  45 
  46 // Check order in EXPAND_CURRENT_PHASES
  47 STATIC_ASSERT(ConcurrentGCPhaseManager::UNCONSTRAINED_PHASE <
  48               ConcurrentGCPhaseManager::IDLE_PHASE);
  49 
  50 #define EXPAND_CONCURRENT_PHASES(expander)                              \
  51   expander(ANY, = ConcurrentGCPhaseManager::UNCONSTRAINED_PHASE, NULL)  \
  52   expander(IDLE, = ConcurrentGCPhaseManager::IDLE_PHASE, NULL)          \
  53   expander(CONCURRENT_CYCLE,, "Concurrent Cycle")                       \
  54   expander(CLEAR_CLAIMED_MARKS,, "Concurrent Clear Claimed Marks")      \
  55   expander(SCAN_ROOT_REGIONS,, "Concurrent Scan Root Regions")          \
  56   expander(CONCURRENT_MARK,, "Concurrent Mark")                         \
  57   expander(MARK_FROM_ROOTS,, "Concurrent Mark From Roots")              \
  58   expander(BEFORE_REMARK,, NULL)                                        \
  59   expander(REMARK,, NULL)                                               \
  60   expander(CREATE_LIVE_DATA,, "Concurrent Create Live Data")            \
  61   expander(COMPLETE_CLEANUP,, "Concurrent Complete Cleanup")            \
  62   expander(CLEANUP_FOR_NEXT_MARK,, "Concurrent Cleanup for Next Mark")  \
  63   /* */
  64 
  65 class G1ConcurrentPhase : public AllStatic {
  66 public:
  67   enum {
  68 #define CONCURRENT_PHASE_ENUM(tag, value, ignore_title) tag value,
  69     EXPAND_CONCURRENT_PHASES(CONCURRENT_PHASE_ENUM)
  70 #undef CONCURRENT_PHASE_ENUM
  71     PHASE_ID_LIMIT
  72   };
  73 };
  74 
  75 // The CM thread is created when the G1 garbage collector is used
  76 
  77 ConcurrentMarkThread::ConcurrentMarkThread(G1ConcurrentMark* cm) :
  78   ConcurrentGCThread(),
  79   _cm(cm),
  80   _state(Idle),
  81   _phase_manager_stack(),
  82   _vtime_accum(0.0),
  83   _vtime_mark_accum(0.0) {
  84 
  85   set_name("G1 Main Marker");
  86   create_and_start();
  87 }
  88 
  89 class CMCheckpointRootsFinalClosure: public VoidClosure {
  90 
  91   G1ConcurrentMark* _cm;
  92 public:
  93 
  94   CMCheckpointRootsFinalClosure(G1ConcurrentMark* cm) :
  95     _cm(cm) {}
  96 
  97   void do_void(){
  98     _cm->checkpoint_roots_final(false); // !clear_all_soft_refs
  99   }
 100 };
 101 
 102 class CMCleanUp: public VoidClosure {
 103   G1ConcurrentMark* _cm;
 104 public:
 105 
 106   CMCleanUp(G1ConcurrentMark* cm) :
 107     _cm(cm) {}
 108 
 109   void do_void(){
 110     _cm->cleanup();
 111   }
 112 };
 113 
 114 double ConcurrentMarkThread::mmu_sleep_time(G1Policy* g1_policy, bool remark) {
 115   // There are 3 reasons to use SuspendibleThreadSetJoiner.
 116   // 1. To avoid concurrency problem.
 117   //    - G1MMUTracker::add_pause(), when_sec() and its variation(when_ms() etc..) can be called
 118   //      concurrently from ConcurrentMarkThread and VMThread.
 119   // 2. If currently a gc is running, but it has not yet updated the MMU,
 120   //    we will not forget to consider that pause in the MMU calculation.
 121   // 3. If currently a gc is running, ConcurrentMarkThread will wait it to be finished.
 122   //    And then sleep for predicted amount of time by delay_to_keep_mmu().
 123   SuspendibleThreadSetJoiner sts_join;
 124 
 125   const G1Analytics* analytics = g1_policy->analytics();
 126   double now = os::elapsedTime();
 127   double prediction_ms = remark ? analytics->predict_remark_time_ms()
 128                                 : analytics->predict_cleanup_time_ms();
 129   G1MMUTracker *mmu_tracker = g1_policy->mmu_tracker();
 130   return mmu_tracker->when_ms(now, prediction_ms);
 131 }
 132 
 133 void ConcurrentMarkThread::delay_to_keep_mmu(G1Policy* g1_policy, bool remark) {
 134   if (g1_policy->adaptive_young_list_length()) {
 135     jlong sleep_time_ms = mmu_sleep_time(g1_policy, remark);
 136     if (!cm()->has_aborted() && sleep_time_ms > 0) {
 137       os::sleep(this, sleep_time_ms, false);
 138     }
 139   }
 140 }
 141 
 142 class G1ConcPhaseTimer : public GCTraceConcTimeImpl<LogLevel::Info, LOG_TAGS(gc, marking)> {
 143   G1ConcurrentMark* _cm;
 144 
 145  public:
 146   G1ConcPhaseTimer(G1ConcurrentMark* cm, const char* title) :
 147     GCTraceConcTimeImpl<LogLevel::Info,  LogTag::_gc, LogTag::_marking>(title),
 148     _cm(cm)
 149   {
 150     _cm->gc_timer_cm()->register_gc_concurrent_start(title);
 151   }
 152 
 153   ~G1ConcPhaseTimer() {
 154     _cm->gc_timer_cm()->register_gc_concurrent_end();
 155   }
 156 };
 157 
 158 static const char* const concurrent_phase_names[] = {
 159 #define CONCURRENT_PHASE_NAME(tag, ignore_value, ignore_title) XSTR(tag),
 160   EXPAND_CONCURRENT_PHASES(CONCURRENT_PHASE_NAME)
 161 #undef CONCURRENT_PHASE_NAME
 162   NULL                          // terminator
 163 };
 164 // Verify dense enum assumption.  +1 for terminator.
 165 STATIC_ASSERT(G1ConcurrentPhase::PHASE_ID_LIMIT + 1 ==
 166               ARRAY_SIZE(concurrent_phase_names));
 167 
 168 // Returns the phase number for name, or a negative value if unknown.
 169 static int lookup_concurrent_phase(const char* name) {
 170   const char* const* names = concurrent_phase_names;
 171   for (uint i = 0; names[i] != NULL; ++i) {
 172     if (strcmp(name, names[i]) == 0) {
 173       return static_cast<int>(i);
 174     }
 175   }
 176   return -1;
 177 }
 178 
 179 // The phase must be valid and must have a title.
 180 static const char* lookup_concurrent_phase_title(int phase) {
 181   static const char* const titles[] = {
 182 #define CONCURRENT_PHASE_TITLE(ignore_tag, ignore_value, title) title,
 183     EXPAND_CONCURRENT_PHASES(CONCURRENT_PHASE_TITLE)
 184 #undef CONCURRENT_PHASE_TITLE
 185   };
 186   // Verify dense enum assumption.
 187   STATIC_ASSERT(G1ConcurrentPhase::PHASE_ID_LIMIT == ARRAY_SIZE(titles));
 188 
 189   assert(0 <= phase, "precondition");
 190   assert((uint)phase < ARRAY_SIZE(titles), "precondition");
 191   const char* title = titles[phase];
 192   assert(title != NULL, "precondition");
 193   return title;
 194 }
 195 
 196 class G1ConcPhaseManager : public StackObj {
 197   G1ConcurrentMark* _cm;
 198   ConcurrentGCPhaseManager _manager;
 199 
 200 public:
 201   G1ConcPhaseManager(int phase, ConcurrentMarkThread* thread) :
 202     _cm(thread->cm()),
 203     _manager(phase, thread->phase_manager_stack())
 204   { }
 205 
 206   ~G1ConcPhaseManager() {
 207     // Deactivate the manager if marking aborted, to avoid blocking on
 208     // phase exit when the phase has been requested.
 209     if (_cm->has_aborted()) {
 210       _manager.deactivate();
 211     }
 212   }
 213 
 214   void set_phase(int phase, bool force) {
 215     _manager.set_phase(phase, force);
 216   }
 217 };
 218 
 219 // Combine phase management and timing into one convenient utility.
 220 class G1ConcPhase : public StackObj {
 221   G1ConcPhaseTimer _timer;
 222   G1ConcPhaseManager _manager;
 223 
 224 public:
 225   G1ConcPhase(int phase, ConcurrentMarkThread* thread) :
 226     _timer(thread->cm(), lookup_concurrent_phase_title(phase)),
 227     _manager(phase, thread)
 228   { }
 229 };
 230 
 231 const char* const* ConcurrentMarkThread::concurrent_phases() const {
 232   return concurrent_phase_names;
 233 }
 234 
 235 bool ConcurrentMarkThread::request_concurrent_phase(const char* phase_name) {
 236   int phase = lookup_concurrent_phase(phase_name);
 237   if (phase < 0) return false;
 238 
 239   while (!ConcurrentGCPhaseManager::wait_for_phase(phase,
 240                                                    phase_manager_stack())) {
 241     assert(phase != G1ConcurrentPhase::ANY, "Wait for ANY phase must succeed");
 242     if ((phase != G1ConcurrentPhase::IDLE) && !during_cycle()) {
 243       // If idle and the goal is !idle, start a collection.
 244       G1CollectedHeap::heap()->collect(GCCause::_wb_conc_mark);
 245     }
 246   }
 247   return true;
 248 }
 249 
 250 void ConcurrentMarkThread::run_service() {
 251   _vtime_start = os::elapsedVTime();
 252 
 253   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 254   G1Policy* g1_policy = g1h->g1_policy();
 255 
 256   G1ConcPhaseManager cpmanager(G1ConcurrentPhase::IDLE, this);
 257 
 258   while (!should_terminate()) {
 259     // wait until started is set.
 260     sleepBeforeNextCycle();
 261     if (should_terminate()) {
 262       break;
 263     }
 264 
 265     cpmanager.set_phase(G1ConcurrentPhase::CONCURRENT_CYCLE, false /* force */);
 266 
 267     GCIdMark gc_id_mark;
 268 
 269     cm()->concurrent_cycle_start();
 270 
 271     GCTraceConcTime(Info, gc) tt("Concurrent Cycle");
 272     {
 273       ResourceMark rm;
 274       HandleMark   hm;
 275       double cycle_start = os::elapsedVTime();
 276 
 277       {
 278         G1ConcPhase p(G1ConcurrentPhase::CLEAR_CLAIMED_MARKS, this);
 279         ClassLoaderDataGraph::clear_claimed_marks();
 280       }
 281 
 282       // We have to ensure that we finish scanning the root regions
 283       // before the next GC takes place. To ensure this we have to
 284       // make sure that we do not join the STS until the root regions
 285       // have been scanned. If we did then it's possible that a
 286       // subsequent GC could block us from joining the STS and proceed
 287       // without the root regions have been scanned which would be a
 288       // correctness issue.
 289 
 290       {
 291         G1ConcPhase p(G1ConcurrentPhase::SCAN_ROOT_REGIONS, this);
 292         _cm->scan_root_regions();
 293       }
 294 
 295       // It would be nice to use the G1ConcPhase class here but
 296       // the "end" logging is inside the loop and not at the end of
 297       // a scope. Also, the timer doesn't support nesting.
 298       // Mimicking the same log output instead.
 299       {
 300         G1ConcPhaseManager mark_manager(G1ConcurrentPhase::CONCURRENT_MARK, this);
 301         jlong mark_start = os::elapsed_counter();
 302         const char* cm_title =
 303           lookup_concurrent_phase_title(G1ConcurrentPhase::CONCURRENT_MARK);
 304         log_info(gc, marking)("%s (%.3fs)",
 305                               cm_title,
 306                               TimeHelper::counter_to_seconds(mark_start));
 307         for (uint iter = 1; !cm()->has_aborted(); ++iter) {
 308           // Concurrent marking.
 309           {
 310             G1ConcPhase p(G1ConcurrentPhase::MARK_FROM_ROOTS, this);
 311             _cm->mark_from_roots();
 312           }
 313           if (cm()->has_aborted()) break;
 314 
 315           // Provide a control point after mark_from_roots.
 316           {
 317             G1ConcPhaseManager p(G1ConcurrentPhase::BEFORE_REMARK, this);
 318           }
 319           if (cm()->has_aborted()) break;
 320 
 321           // Delay remark pause for MMU.
 322           double mark_end_time = os::elapsedVTime();
 323           jlong mark_end = os::elapsed_counter();
 324           _vtime_mark_accum += (mark_end_time - cycle_start);
 325           delay_to_keep_mmu(g1_policy, true /* remark */);
 326           if (cm()->has_aborted()) break;
 327 
 328           // Pause Remark.
 329           log_info(gc, marking)("%s (%.3fs, %.3fs) %.3fms",
 330                                 cm_title,
 331                                 TimeHelper::counter_to_seconds(mark_start),
 332                                 TimeHelper::counter_to_seconds(mark_end),
 333                                 TimeHelper::counter_to_millis(mark_end - mark_start));
 334           mark_manager.set_phase(G1ConcurrentPhase::REMARK, false);
 335           CMCheckpointRootsFinalClosure final_cl(_cm);
 336           VM_CGC_Operation op(&final_cl, "Pause Remark");
 337           VMThread::execute(&op);
 338           if (cm()->has_aborted()) {
 339             break;
 340           } else if (!cm()->restart_for_overflow()) {
 341             break;              // Exit loop if no restart requested.
 342           } else {
 343             // Loop to restart for overflow.
 344             mark_manager.set_phase(G1ConcurrentPhase::CONCURRENT_MARK, false);
 345             log_info(gc, marking)("%s Restart for Mark Stack Overflow (iteration #%u)",
 346                                   cm_title, iter);
 347           }
 348         }
 349       }
 350 
 351       if (!cm()->has_aborted()) {
 352         G1ConcPhase p(G1ConcurrentPhase::CREATE_LIVE_DATA, this);
 353         cm()->create_live_data();
 354       }
 355 
 356       double end_time = os::elapsedVTime();
 357       // Update the total virtual time before doing this, since it will try
 358       // to measure it to get the vtime for this marking.  We purposely
 359       // neglect the presumably-short "completeCleanup" phase here.
 360       _vtime_accum = (end_time - _vtime_start);
 361 
 362       if (!cm()->has_aborted()) {
 363         delay_to_keep_mmu(g1_policy, false /* cleanup */);
 364 
 365         if (!cm()->has_aborted()) {
 366           CMCleanUp cl_cl(_cm);
 367           VM_CGC_Operation op(&cl_cl, "Pause Cleanup");
 368           VMThread::execute(&op);
 369         }
 370       } else {
 371         // We don't want to update the marking status if a GC pause
 372         // is already underway.
 373         SuspendibleThreadSetJoiner sts_join;
 374         g1h->collector_state()->set_mark_in_progress(false);
 375       }
 376 
 377       // Check if cleanup set the free_regions_coming flag. If it
 378       // hasn't, we can just skip the next step.
 379       if (g1h->free_regions_coming()) {
 380         // The following will finish freeing up any regions that we
 381         // found to be empty during cleanup. We'll do this part
 382         // without joining the suspendible set. If an evacuation pause
 383         // takes place, then we would carry on freeing regions in
 384         // case they are needed by the pause. If a Full GC takes
 385         // place, it would wait for us to process the regions
 386         // reclaimed by cleanup.
 387 
 388         // Now do the concurrent cleanup operation.
 389         G1ConcPhase p(G1ConcurrentPhase::COMPLETE_CLEANUP, this);
 390         _cm->complete_cleanup();
 391 
 392         // Notify anyone who's waiting that there are no more free
 393         // regions coming. We have to do this before we join the STS
 394         // (in fact, we should not attempt to join the STS in the
 395         // interval between finishing the cleanup pause and clearing
 396         // the free_regions_coming flag) otherwise we might deadlock:
 397         // a GC worker could be blocked waiting for the notification
 398         // whereas this thread will be blocked for the pause to finish
 399         // while it's trying to join the STS, which is conditional on
 400         // the GC workers finishing.
 401         g1h->reset_free_regions_coming();
 402       }
 403       guarantee(cm()->cleanup_list_is_empty(),
 404                 "at this point there should be no regions on the cleanup list");
 405 
 406       // There is a tricky race before recording that the concurrent
 407       // cleanup has completed and a potential Full GC starting around
 408       // the same time. We want to make sure that the Full GC calls
 409       // abort() on concurrent mark after
 410       // record_concurrent_mark_cleanup_completed(), since abort() is
 411       // the method that will reset the concurrent mark state. If we
 412       // end up calling record_concurrent_mark_cleanup_completed()
 413       // after abort() then we might incorrectly undo some of the work
 414       // abort() did. Checking the has_aborted() flag after joining
 415       // the STS allows the correct ordering of the two methods. There
 416       // are two scenarios:
 417       //
 418       // a) If we reach here before the Full GC, the fact that we have
 419       // joined the STS means that the Full GC cannot start until we
 420       // leave the STS, so record_concurrent_mark_cleanup_completed()
 421       // will complete before abort() is called.
 422       //
 423       // b) If we reach here during the Full GC, we'll be held up from
 424       // joining the STS until the Full GC is done, which means that
 425       // abort() will have completed and has_aborted() will return
 426       // true to prevent us from calling
 427       // record_concurrent_mark_cleanup_completed() (and, in fact, it's
 428       // not needed any more as the concurrent mark state has been
 429       // already reset).
 430       {
 431         SuspendibleThreadSetJoiner sts_join;
 432         if (!cm()->has_aborted()) {
 433           g1_policy->record_concurrent_mark_cleanup_completed();
 434         } else {
 435           log_info(gc, marking)("Concurrent Mark Abort");
 436         }
 437       }
 438 
 439       // We now want to allow clearing of the marking bitmap to be
 440       // suspended by a collection pause.
 441       // We may have aborted just before the remark. Do not bother clearing the
 442       // bitmap then, as it has been done during mark abort.
 443       if (!cm()->has_aborted()) {
 444         G1ConcPhase p(G1ConcurrentPhase::CLEANUP_FOR_NEXT_MARK, this);
 445         _cm->cleanup_for_next_mark();
 446       } else {
 447         assert(!G1VerifyBitmaps || _cm->next_mark_bitmap_is_clear(), "Next mark bitmap must be clear");
 448       }
 449     }
 450 
 451     // Update the number of full collections that have been
 452     // completed. This will also notify the FullGCCount_lock in case a
 453     // Java thread is waiting for a full GC to happen (e.g., it
 454     // called System.gc() with +ExplicitGCInvokesConcurrent).
 455     {
 456       SuspendibleThreadSetJoiner sts_join;
 457       g1h->increment_old_marking_cycles_completed(true /* concurrent */);
 458 
 459       cm()->concurrent_cycle_end();
 460     }
 461 
 462     cpmanager.set_phase(G1ConcurrentPhase::IDLE, cm()->has_aborted() /* force */);
 463   }
 464   _cm->root_regions()->cancel_scan();
 465 }
 466 
 467 void ConcurrentMarkThread::stop_service() {
 468   MutexLockerEx ml(CGC_lock, Mutex::_no_safepoint_check_flag);
 469   CGC_lock->notify_all();
 470 }
 471 
 472 void ConcurrentMarkThread::sleepBeforeNextCycle() {
 473   // We join here because we don't want to do the "shouldConcurrentMark()"
 474   // below while the world is otherwise stopped.
 475   assert(!in_progress(), "should have been cleared");
 476 
 477   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
 478   while (!started() && !should_terminate()) {
 479     CGC_lock->wait(Mutex::_no_safepoint_check_flag);
 480   }
 481 
 482   if (started()) {
 483     set_in_progress();
 484   }
 485 }