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