1 /*
   2  * Copyright (c) 2001, 2019, 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/classLoaderDataGraph.hpp"
  27 #include "gc/g1/g1Analytics.hpp"
  28 #include "gc/g1/g1CollectedHeap.inline.hpp"
  29 #include "gc/g1/g1ConcurrentMark.inline.hpp"
  30 #include "gc/g1/g1ConcurrentMarkThread.inline.hpp"
  31 #include "gc/g1/g1MMUTracker.hpp"
  32 #include "gc/g1/g1Policy.hpp"
  33 #include "gc/g1/g1RemSet.hpp"
  34 #include "gc/g1/g1Trace.hpp"
  35 #include "gc/g1/g1VMOperations.hpp"
  36 #include "gc/shared/concurrentGCPhaseManager.hpp"
  37 #include "gc/shared/gcId.hpp"
  38 #include "gc/shared/gcTraceTime.inline.hpp"
  39 #include "gc/shared/suspendibleThreadSet.hpp"
  40 #include "logging/log.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "runtime/handles.inline.hpp"
  43 #include "runtime/mutexLocker.inline.hpp"
  44 #include "runtime/vmThread.hpp"
  45 #include "utilities/debug.hpp"
  46 
  47 // ======= Concurrent Mark Thread ========
  48 
  49 // Check order in EXPAND_CURRENT_PHASES
  50 STATIC_ASSERT(ConcurrentGCPhaseManager::UNCONSTRAINED_PHASE <
  51               ConcurrentGCPhaseManager::IDLE_PHASE);
  52 
  53 #define EXPAND_CONCURRENT_PHASES(expander)                                 \
  54   expander(ANY, = ConcurrentGCPhaseManager::UNCONSTRAINED_PHASE, NULL)     \
  55   expander(IDLE, = ConcurrentGCPhaseManager::IDLE_PHASE, NULL)             \
  56   expander(CONCURRENT_CYCLE,, "Concurrent Cycle")                          \
  57   expander(CLEAR_CLAIMED_MARKS,, "Concurrent Clear Claimed Marks")         \
  58   expander(SCAN_ROOT_REGIONS,, "Concurrent Scan Root Regions")             \
  59   expander(CONCURRENT_MARK,, "Concurrent Mark")                            \
  60   expander(MARK_FROM_ROOTS,, "Concurrent Mark From Roots")                 \
  61   expander(PRECLEAN,, "Concurrent Preclean")                               \
  62   expander(BEFORE_REMARK,, NULL)                                           \
  63   expander(REMARK,, NULL)                                                  \
  64   expander(REBUILD_REMEMBERED_SETS,, "Concurrent Rebuild Remembered Sets") \
  65   expander(CLEANUP_FOR_NEXT_MARK,, "Concurrent Cleanup for Next Mark")     \
  66   /* */
  67 
  68 class G1ConcurrentPhase : public AllStatic {
  69 public:
  70   enum {
  71 #define CONCURRENT_PHASE_ENUM(tag, value, ignore_title) tag value,
  72     EXPAND_CONCURRENT_PHASES(CONCURRENT_PHASE_ENUM)
  73 #undef CONCURRENT_PHASE_ENUM
  74     PHASE_ID_LIMIT
  75   };
  76 };
  77 
  78 G1ConcurrentMarkThread::G1ConcurrentMarkThread(G1ConcurrentMark* cm) :
  79   ConcurrentGCThread(),
  80   _vtime_start(0.0),
  81   _vtime_accum(0.0),
  82   _vtime_mark_accum(0.0),
  83   _cm(cm),
  84   _state(Idle),
  85   _phase_manager_stack() {
  86 
  87   set_name("G1 Main Marker");
  88   create_and_start();
  89 }
  90 
  91 class CMRemark : public VoidClosure {
  92   G1ConcurrentMark* _cm;
  93 public:
  94   CMRemark(G1ConcurrentMark* cm) : _cm(cm) {}
  95 
  96   void do_void(){
  97     _cm->remark();
  98   }
  99 };
 100 
 101 class CMCleanup : public VoidClosure {
 102   G1ConcurrentMark* _cm;
 103 public:
 104   CMCleanup(G1ConcurrentMark* cm) : _cm(cm) {}
 105 
 106   void do_void(){
 107     _cm->cleanup();
 108   }
 109 };
 110 
 111 double G1ConcurrentMarkThread::mmu_delay_end(G1Policy* g1_policy, bool remark) {
 112   // There are 3 reasons to use SuspendibleThreadSetJoiner.
 113   // 1. To avoid concurrency problem.
 114   //    - G1MMUTracker::add_pause(), when_sec() and its variation(when_ms() etc..) can be called
 115   //      concurrently from ConcurrentMarkThread and VMThread.
 116   // 2. If currently a gc is running, but it has not yet updated the MMU,
 117   //    we will not forget to consider that pause in the MMU calculation.
 118   // 3. If currently a gc is running, ConcurrentMarkThread will wait it to be finished.
 119   //    And then sleep for predicted amount of time by delay_to_keep_mmu().
 120   SuspendibleThreadSetJoiner sts_join;
 121 
 122   const G1Analytics* analytics = g1_policy->analytics();
 123   double prediction_ms = remark ? analytics->predict_remark_time_ms()
 124                                 : analytics->predict_cleanup_time_ms();
 125   double prediction = prediction_ms / MILLIUNITS;
 126   G1MMUTracker *mmu_tracker = g1_policy->mmu_tracker();
 127   double now = os::elapsedTime();
 128   return now + mmu_tracker->when_sec(now, prediction);
 129 }
 130 
 131 void G1ConcurrentMarkThread::delay_to_keep_mmu(G1Policy* g1_policy, bool remark) {
 132   if (g1_policy->use_adaptive_young_list_length()) {
 133     double delay_end_sec = mmu_delay_end(g1_policy, remark);
 134     // Wait for timeout or thread termination request.
 135     MonitorLocker ml(CGC_lock, Monitor::_no_safepoint_check_flag);
 136     while (!_cm->has_aborted()) {
 137       double sleep_time_sec = (delay_end_sec - os::elapsedTime());
 138       jlong sleep_time_ms = ceil(sleep_time_sec * MILLIUNITS);
 139       if (sleep_time_ms <= 0) {
 140         break;                  // Passed end time.
 141       } else if (ml.wait(sleep_time_ms, Monitor::_no_safepoint_check_flag)) {
 142         break;                  // Timeout => reached end time.
 143       } else if (should_terminate()) {
 144         break;                  // Wakeup for pending termination request.
 145       }
 146       // Other (possibly spurious) wakeup.  Retry with updated sleep time.
 147     }
 148   }
 149 }
 150 
 151 class G1ConcPhaseTimer : public GCTraceConcTimeImpl<LogLevel::Info, LOG_TAGS(gc, marking)> {
 152   G1ConcurrentMark* _cm;
 153 
 154  public:
 155   G1ConcPhaseTimer(G1ConcurrentMark* cm, const char* title) :
 156     GCTraceConcTimeImpl<LogLevel::Info,  LogTag::_gc, LogTag::_marking>(title),
 157     _cm(cm)
 158   {
 159     _cm->gc_timer_cm()->register_gc_concurrent_start(title);
 160   }
 161 
 162   ~G1ConcPhaseTimer() {
 163     _cm->gc_timer_cm()->register_gc_concurrent_end();
 164   }
 165 };
 166 
 167 static const char* const concurrent_phase_names[] = {
 168 #define CONCURRENT_PHASE_NAME(tag, ignore_value, ignore_title) XSTR(tag),
 169   EXPAND_CONCURRENT_PHASES(CONCURRENT_PHASE_NAME)
 170 #undef CONCURRENT_PHASE_NAME
 171   NULL                          // terminator
 172 };
 173 // Verify dense enum assumption.  +1 for terminator.
 174 STATIC_ASSERT(G1ConcurrentPhase::PHASE_ID_LIMIT + 1 ==
 175               ARRAY_SIZE(concurrent_phase_names));
 176 
 177 // Returns the phase number for name, or a negative value if unknown.
 178 static int lookup_concurrent_phase(const char* name) {
 179   const char* const* names = concurrent_phase_names;
 180   for (uint i = 0; names[i] != NULL; ++i) {
 181     if (strcmp(name, names[i]) == 0) {
 182       return static_cast<int>(i);
 183     }
 184   }
 185   return -1;
 186 }
 187 
 188 // The phase must be valid and must have a title.
 189 static const char* lookup_concurrent_phase_title(int phase) {
 190   static const char* const titles[] = {
 191 #define CONCURRENT_PHASE_TITLE(ignore_tag, ignore_value, title) title,
 192     EXPAND_CONCURRENT_PHASES(CONCURRENT_PHASE_TITLE)
 193 #undef CONCURRENT_PHASE_TITLE
 194   };
 195   // Verify dense enum assumption.
 196   STATIC_ASSERT(G1ConcurrentPhase::PHASE_ID_LIMIT == ARRAY_SIZE(titles));
 197 
 198   assert(0 <= phase, "precondition");
 199   assert((uint)phase < ARRAY_SIZE(titles), "precondition");
 200   const char* title = titles[phase];
 201   assert(title != NULL, "precondition");
 202   return title;
 203 }
 204 
 205 class G1ConcPhaseManager : public StackObj {
 206   G1ConcurrentMark* _cm;
 207   ConcurrentGCPhaseManager _manager;
 208 
 209 public:
 210   G1ConcPhaseManager(int phase, G1ConcurrentMarkThread* thread) :
 211     _cm(thread->cm()),
 212     _manager(phase, thread->phase_manager_stack())
 213   { }
 214 
 215   ~G1ConcPhaseManager() {
 216     // Deactivate the manager if marking aborted, to avoid blocking on
 217     // phase exit when the phase has been requested.
 218     if (_cm->has_aborted()) {
 219       _manager.deactivate();
 220     }
 221   }
 222 
 223   void set_phase(int phase, bool force) {
 224     _manager.set_phase(phase, force);
 225   }
 226 };
 227 
 228 // Combine phase management and timing into one convenient utility.
 229 class G1ConcPhase : public StackObj {
 230   G1ConcPhaseTimer _timer;
 231   G1ConcPhaseManager _manager;
 232 
 233 public:
 234   G1ConcPhase(int phase, G1ConcurrentMarkThread* thread) :
 235     _timer(thread->cm(), lookup_concurrent_phase_title(phase)),
 236     _manager(phase, thread)
 237   { }
 238 };
 239 
 240 bool G1ConcurrentMarkThread::request_concurrent_phase(const char* phase_name) {
 241   int phase = lookup_concurrent_phase(phase_name);
 242   if (phase < 0) return false;
 243 
 244   while (!ConcurrentGCPhaseManager::wait_for_phase(phase,
 245                                                    phase_manager_stack())) {
 246     assert(phase != G1ConcurrentPhase::ANY, "Wait for ANY phase must succeed");
 247     if ((phase != G1ConcurrentPhase::IDLE) && !during_cycle()) {
 248       // If idle and the goal is !idle, start a collection.
 249       G1CollectedHeap::heap()->collect(GCCause::_wb_conc_mark);
 250     }
 251   }
 252   return true;
 253 }
 254 
 255 void G1ConcurrentMarkThread::run_service() {
 256   _vtime_start = os::elapsedVTime();
 257 
 258   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 259   G1Policy* policy = g1h->policy();
 260 
 261   G1ConcPhaseManager cpmanager(G1ConcurrentPhase::IDLE, this);
 262 
 263   while (!should_terminate()) {
 264     // wait until started is set.
 265     sleep_before_next_cycle();
 266     if (should_terminate()) {
 267       break;
 268     }
 269 
 270     cpmanager.set_phase(G1ConcurrentPhase::CONCURRENT_CYCLE, false /* force */);
 271 
 272     GCIdMark gc_id_mark;
 273 
 274     _cm->concurrent_cycle_start();
 275 
 276     GCTraceConcTime(Info, gc) tt("Concurrent Cycle");
 277     {
 278       ResourceMark rm;
 279       HandleMark   hm;
 280       double cycle_start = os::elapsedVTime();
 281 
 282       {
 283         G1ConcPhase p(G1ConcurrentPhase::CLEAR_CLAIMED_MARKS, this);
 284         ClassLoaderDataGraph::clear_claimed_marks();
 285       }
 286 
 287       // We have to ensure that we finish scanning the root regions
 288       // before the next GC takes place. To ensure this we have to
 289       // make sure that we do not join the STS until the root regions
 290       // have been scanned. If we did then it's possible that a
 291       // subsequent GC could block us from joining the STS and proceed
 292       // without the root regions have been scanned which would be a
 293       // correctness issue.
 294 
 295       {
 296         G1ConcPhase p(G1ConcurrentPhase::SCAN_ROOT_REGIONS, this);
 297         _cm->scan_root_regions();
 298       }
 299 
 300       // It would be nice to use the G1ConcPhase class here but
 301       // the "end" logging is inside the loop and not at the end of
 302       // a scope. Also, the timer doesn't support nesting.
 303       // Mimicking the same log output instead.
 304       {
 305         G1ConcPhaseManager mark_manager(G1ConcurrentPhase::CONCURRENT_MARK, this);
 306         jlong mark_start = os::elapsed_counter();
 307         const char* cm_title = lookup_concurrent_phase_title(G1ConcurrentPhase::CONCURRENT_MARK);
 308         log_info(gc, marking)("%s (%.3fs)",
 309                               cm_title,
 310                               TimeHelper::counter_to_seconds(mark_start));
 311         for (uint iter = 1; !_cm->has_aborted(); ++iter) {
 312           // Concurrent marking.
 313           {
 314             G1ConcPhase p(G1ConcurrentPhase::MARK_FROM_ROOTS, this);
 315             _cm->mark_from_roots();
 316           }
 317           if (_cm->has_aborted()) {
 318             break;
 319           }
 320 
 321           if (G1UseReferencePrecleaning) {
 322             G1ConcPhase p(G1ConcurrentPhase::PRECLEAN, this);
 323             _cm->preclean();
 324           }
 325 
 326           // Provide a control point before remark.
 327           {
 328             G1ConcPhaseManager p(G1ConcurrentPhase::BEFORE_REMARK, this);
 329           }
 330           if (_cm->has_aborted()) {
 331             break;
 332           }
 333 
 334           // Delay remark pause for MMU.
 335           double mark_end_time = os::elapsedVTime();
 336           jlong mark_end = os::elapsed_counter();
 337           _vtime_mark_accum += (mark_end_time - cycle_start);
 338           delay_to_keep_mmu(policy, true /* remark */);
 339           if (_cm->has_aborted()) {
 340             break;
 341           }
 342 
 343           // Pause Remark.
 344           log_info(gc, marking)("%s (%.3fs, %.3fs) %.3fms",
 345                                 cm_title,
 346                                 TimeHelper::counter_to_seconds(mark_start),
 347                                 TimeHelper::counter_to_seconds(mark_end),
 348                                 TimeHelper::counter_to_millis(mark_end - mark_start));
 349           mark_manager.set_phase(G1ConcurrentPhase::REMARK, false);
 350           CMRemark cl(_cm);
 351           VM_G1Concurrent op(&cl, "Pause Remark");
 352           VMThread::execute(&op);
 353           if (_cm->has_aborted()) {
 354             break;
 355           } else if (!_cm->restart_for_overflow()) {
 356             break;              // Exit loop if no restart requested.
 357           } else {
 358             // Loop to restart for overflow.
 359             mark_manager.set_phase(G1ConcurrentPhase::CONCURRENT_MARK, false);
 360             log_info(gc, marking)("%s Restart for Mark Stack Overflow (iteration #%u)",
 361                                   cm_title, iter);
 362           }
 363         }
 364       }
 365 
 366       if (!_cm->has_aborted()) {
 367         G1ConcPhase p(G1ConcurrentPhase::REBUILD_REMEMBERED_SETS, this);
 368         _cm->rebuild_rem_set_concurrently();
 369       }
 370 
 371       double end_time = os::elapsedVTime();
 372       // Update the total virtual time before doing this, since it will try
 373       // to measure it to get the vtime for this marking.
 374       _vtime_accum = (end_time - _vtime_start);
 375 
 376       if (!_cm->has_aborted()) {
 377         delay_to_keep_mmu(policy, false /* cleanup */);
 378       }
 379 
 380       if (!_cm->has_aborted()) {
 381         CMCleanup cl_cl(_cm);
 382         VM_G1Concurrent op(&cl_cl, "Pause Cleanup");
 383         VMThread::execute(&op);
 384       }
 385 
 386       // We now want to allow clearing of the marking bitmap to be
 387       // suspended by a collection pause.
 388       // We may have aborted just before the remark. Do not bother clearing the
 389       // bitmap then, as it has been done during mark abort.
 390       if (!_cm->has_aborted()) {
 391         G1ConcPhase p(G1ConcurrentPhase::CLEANUP_FOR_NEXT_MARK, this);
 392         _cm->cleanup_for_next_mark();
 393       }
 394     }
 395 
 396     // Update the number of full collections that have been
 397     // completed. This will also notify the FullGCCount_lock in case a
 398     // Java thread is waiting for a full GC to happen (e.g., it
 399     // called System.gc() with +ExplicitGCInvokesConcurrent).
 400     {
 401       SuspendibleThreadSetJoiner sts_join;
 402       g1h->increment_old_marking_cycles_completed(true /* concurrent */);
 403 
 404       _cm->concurrent_cycle_end();
 405     }
 406 
 407     cpmanager.set_phase(G1ConcurrentPhase::IDLE, _cm->has_aborted() /* force */);
 408   }
 409   _cm->root_regions()->cancel_scan();
 410 }
 411 
 412 void G1ConcurrentMarkThread::stop_service() {
 413   MutexLocker ml(CGC_lock, Mutex::_no_safepoint_check_flag);
 414   CGC_lock->notify_all();
 415 }
 416 
 417 
 418 void G1ConcurrentMarkThread::sleep_before_next_cycle() {
 419   // We join here because we don't want to do the "shouldConcurrentMark()"
 420   // below while the world is otherwise stopped.
 421   assert(!in_progress(), "should have been cleared");
 422 
 423   MonitorLocker ml(CGC_lock, Mutex::_no_safepoint_check_flag);
 424   while (!started() && !should_terminate()) {
 425     ml.wait();
 426   }
 427 
 428   if (started()) {
 429     set_in_progress();
 430   }
 431 }