1 /* 2 * Copyright (c) 2001, 2014, 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 "classfile/stringTable.hpp" 28 #include "classfile/systemDictionary.hpp" 29 #include "code/codeCache.hpp" 30 #include "gc_implementation/shared/adaptiveSizePolicy.hpp" 31 #include "gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.hpp" 32 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp" 33 #include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp" 34 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.inline.hpp" 35 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp" 36 #include "gc_implementation/concurrentMarkSweep/vmCMSOperations.hpp" 37 #include "gc_implementation/parNew/parNewGeneration.hpp" 38 #include "gc_implementation/shared/collectorCounters.hpp" 39 #include "gc_implementation/shared/gcTimer.hpp" 40 #include "gc_implementation/shared/gcTrace.hpp" 41 #include "gc_implementation/shared/gcTraceTime.hpp" 42 #include "gc_implementation/shared/isGCActiveMark.hpp" 43 #include "gc_interface/collectedHeap.inline.hpp" 44 #include "memory/allocation.hpp" 45 #include "memory/cardTableRS.hpp" 46 #include "memory/collectorPolicy.hpp" 47 #include "memory/gcLocker.inline.hpp" 48 #include "memory/genCollectedHeap.hpp" 49 #include "memory/genMarkSweep.hpp" 50 #include "memory/genOopClosures.inline.hpp" 51 #include "memory/iterator.inline.hpp" 52 #include "memory/padded.hpp" 53 #include "memory/referencePolicy.hpp" 54 #include "memory/resourceArea.hpp" 55 #include "memory/tenuredGeneration.hpp" 56 #include "oops/oop.inline.hpp" 57 #include "prims/jvmtiExport.hpp" 58 #include "runtime/atomic.inline.hpp" 59 #include "runtime/globals_extension.hpp" 60 #include "runtime/handles.inline.hpp" 61 #include "runtime/java.hpp" 62 #include "runtime/orderAccess.inline.hpp" 63 #include "runtime/vmThread.hpp" 64 #include "services/memoryService.hpp" 65 #include "services/runtimeService.hpp" 66 67 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 68 69 // statics 70 CMSCollector* ConcurrentMarkSweepGeneration::_collector = NULL; 71 bool CMSCollector::_full_gc_requested = false; 72 GCCause::Cause CMSCollector::_full_gc_cause = GCCause::_no_gc; 73 74 ////////////////////////////////////////////////////////////////// 75 // In support of CMS/VM thread synchronization 76 ////////////////////////////////////////////////////////////////// 77 // We split use of the CGC_lock into 2 "levels". 78 // The low-level locking is of the usual CGC_lock monitor. We introduce 79 // a higher level "token" (hereafter "CMS token") built on top of the 80 // low level monitor (hereafter "CGC lock"). 81 // The token-passing protocol gives priority to the VM thread. The 82 // CMS-lock doesn't provide any fairness guarantees, but clients 83 // should ensure that it is only held for very short, bounded 84 // durations. 85 // 86 // When either of the CMS thread or the VM thread is involved in 87 // collection operations during which it does not want the other 88 // thread to interfere, it obtains the CMS token. 89 // 90 // If either thread tries to get the token while the other has 91 // it, that thread waits. However, if the VM thread and CMS thread 92 // both want the token, then the VM thread gets priority while the 93 // CMS thread waits. This ensures, for instance, that the "concurrent" 94 // phases of the CMS thread's work do not block out the VM thread 95 // for long periods of time as the CMS thread continues to hog 96 // the token. (See bug 4616232). 97 // 98 // The baton-passing functions are, however, controlled by the 99 // flags _foregroundGCShouldWait and _foregroundGCIsActive, 100 // and here the low-level CMS lock, not the high level token, 101 // ensures mutual exclusion. 102 // 103 // Two important conditions that we have to satisfy: 104 // 1. if a thread does a low-level wait on the CMS lock, then it 105 // relinquishes the CMS token if it were holding that token 106 // when it acquired the low-level CMS lock. 107 // 2. any low-level notifications on the low-level lock 108 // should only be sent when a thread has relinquished the token. 109 // 110 // In the absence of either property, we'd have potential deadlock. 111 // 112 // We protect each of the CMS (concurrent and sequential) phases 113 // with the CMS _token_, not the CMS _lock_. 114 // 115 // The only code protected by CMS lock is the token acquisition code 116 // itself, see ConcurrentMarkSweepThread::[de]synchronize(), and the 117 // baton-passing code. 118 // 119 // Unfortunately, i couldn't come up with a good abstraction to factor and 120 // hide the naked CGC_lock manipulation in the baton-passing code 121 // further below. That's something we should try to do. Also, the proof 122 // of correctness of this 2-level locking scheme is far from obvious, 123 // and potentially quite slippery. We have an uneasy suspicion, for instance, 124 // that there may be a theoretical possibility of delay/starvation in the 125 // low-level lock/wait/notify scheme used for the baton-passing because of 126 // potential interference with the priority scheme embodied in the 127 // CMS-token-passing protocol. See related comments at a CGC_lock->wait() 128 // invocation further below and marked with "XXX 20011219YSR". 129 // Indeed, as we note elsewhere, this may become yet more slippery 130 // in the presence of multiple CMS and/or multiple VM threads. XXX 131 132 class CMSTokenSync: public StackObj { 133 private: 134 bool _is_cms_thread; 135 public: 136 CMSTokenSync(bool is_cms_thread): 137 _is_cms_thread(is_cms_thread) { 138 assert(is_cms_thread == Thread::current()->is_ConcurrentGC_thread(), 139 "Incorrect argument to constructor"); 140 ConcurrentMarkSweepThread::synchronize(_is_cms_thread); 141 } 142 143 ~CMSTokenSync() { 144 assert(_is_cms_thread ? 145 ConcurrentMarkSweepThread::cms_thread_has_cms_token() : 146 ConcurrentMarkSweepThread::vm_thread_has_cms_token(), 147 "Incorrect state"); 148 ConcurrentMarkSweepThread::desynchronize(_is_cms_thread); 149 } 150 }; 151 152 // Convenience class that does a CMSTokenSync, and then acquires 153 // upto three locks. 154 class CMSTokenSyncWithLocks: public CMSTokenSync { 155 private: 156 // Note: locks are acquired in textual declaration order 157 // and released in the opposite order 158 MutexLockerEx _locker1, _locker2, _locker3; 159 public: 160 CMSTokenSyncWithLocks(bool is_cms_thread, Mutex* mutex1, 161 Mutex* mutex2 = NULL, Mutex* mutex3 = NULL): 162 CMSTokenSync(is_cms_thread), 163 _locker1(mutex1, Mutex::_no_safepoint_check_flag), 164 _locker2(mutex2, Mutex::_no_safepoint_check_flag), 165 _locker3(mutex3, Mutex::_no_safepoint_check_flag) 166 { } 167 }; 168 169 170 ////////////////////////////////////////////////////////////////// 171 // Concurrent Mark-Sweep Generation ///////////////////////////// 172 ////////////////////////////////////////////////////////////////// 173 174 NOT_PRODUCT(CompactibleFreeListSpace* debug_cms_space;) 175 176 // This struct contains per-thread things necessary to support parallel 177 // young-gen collection. 178 class CMSParGCThreadState: public CHeapObj<mtGC> { 179 public: 180 CFLS_LAB lab; 181 PromotionInfo promo; 182 183 // Constructor. 184 CMSParGCThreadState(CompactibleFreeListSpace* cfls) : lab(cfls) { 185 promo.setSpace(cfls); 186 } 187 }; 188 189 ConcurrentMarkSweepGeneration::ConcurrentMarkSweepGeneration( 190 ReservedSpace rs, size_t initial_byte_size, int level, 191 CardTableRS* ct, bool use_adaptive_freelists, 192 FreeBlockDictionary<FreeChunk>::DictionaryChoice dictionaryChoice) : 193 CardGeneration(rs, initial_byte_size, level, ct), 194 _dilatation_factor(((double)MinChunkSize)/((double)(CollectedHeap::min_fill_size()))), 195 _did_compact(false) 196 { 197 HeapWord* bottom = (HeapWord*) _virtual_space.low(); 198 HeapWord* end = (HeapWord*) _virtual_space.high(); 199 200 _direct_allocated_words = 0; 201 NOT_PRODUCT( 202 _numObjectsPromoted = 0; 203 _numWordsPromoted = 0; 204 _numObjectsAllocated = 0; 205 _numWordsAllocated = 0; 206 ) 207 208 _cmsSpace = new CompactibleFreeListSpace(_bts, MemRegion(bottom, end), 209 use_adaptive_freelists, 210 dictionaryChoice); 211 NOT_PRODUCT(debug_cms_space = _cmsSpace;) 212 if (_cmsSpace == NULL) { 213 vm_exit_during_initialization( 214 "CompactibleFreeListSpace allocation failure"); 215 } 216 _cmsSpace->_gen = this; 217 218 _gc_stats = new CMSGCStats(); 219 220 // Verify the assumption that FreeChunk::_prev and OopDesc::_klass 221 // offsets match. The ability to tell free chunks from objects 222 // depends on this property. 223 debug_only( 224 FreeChunk* junk = NULL; 225 assert(UseCompressedClassPointers || 226 junk->prev_addr() == (void*)(oop(junk)->klass_addr()), 227 "Offset of FreeChunk::_prev within FreeChunk must match" 228 " that of OopDesc::_klass within OopDesc"); 229 ) 230 if (CollectedHeap::use_parallel_gc_threads()) { 231 typedef CMSParGCThreadState* CMSParGCThreadStatePtr; 232 _par_gc_thread_states = 233 NEW_C_HEAP_ARRAY(CMSParGCThreadStatePtr, ParallelGCThreads, mtGC); 234 if (_par_gc_thread_states == NULL) { 235 vm_exit_during_initialization("Could not allocate par gc structs"); 236 } 237 for (uint i = 0; i < ParallelGCThreads; i++) { 238 _par_gc_thread_states[i] = new CMSParGCThreadState(cmsSpace()); 239 if (_par_gc_thread_states[i] == NULL) { 240 vm_exit_during_initialization("Could not allocate par gc structs"); 241 } 242 } 243 } else { 244 _par_gc_thread_states = NULL; 245 } 246 _incremental_collection_failed = false; 247 // The "dilatation_factor" is the expansion that can occur on 248 // account of the fact that the minimum object size in the CMS 249 // generation may be larger than that in, say, a contiguous young 250 // generation. 251 // Ideally, in the calculation below, we'd compute the dilatation 252 // factor as: MinChunkSize/(promoting_gen's min object size) 253 // Since we do not have such a general query interface for the 254 // promoting generation, we'll instead just use the minimum 255 // object size (which today is a header's worth of space); 256 // note that all arithmetic is in units of HeapWords. 257 assert(MinChunkSize >= CollectedHeap::min_fill_size(), "just checking"); 258 assert(_dilatation_factor >= 1.0, "from previous assert"); 259 } 260 261 262 // The field "_initiating_occupancy" represents the occupancy percentage 263 // at which we trigger a new collection cycle. Unless explicitly specified 264 // via CMSInitiatingOccupancyFraction (argument "io" below), it 265 // is calculated by: 266 // 267 // Let "f" be MinHeapFreeRatio in 268 // 269 // _initiating_occupancy = 100-f + 270 // f * (CMSTriggerRatio/100) 271 // where CMSTriggerRatio is the argument "tr" below. 272 // 273 // That is, if we assume the heap is at its desired maximum occupancy at the 274 // end of a collection, we let CMSTriggerRatio of the (purported) free 275 // space be allocated before initiating a new collection cycle. 276 // 277 void ConcurrentMarkSweepGeneration::init_initiating_occupancy(intx io, uintx tr) { 278 assert(io <= 100 && tr <= 100, "Check the arguments"); 279 if (io >= 0) { 280 _initiating_occupancy = (double)io / 100.0; 281 } else { 282 _initiating_occupancy = ((100 - MinHeapFreeRatio) + 283 (double)(tr * MinHeapFreeRatio) / 100.0) 284 / 100.0; 285 } 286 } 287 288 void ConcurrentMarkSweepGeneration::ref_processor_init() { 289 assert(collector() != NULL, "no collector"); 290 collector()->ref_processor_init(); 291 } 292 293 void CMSCollector::ref_processor_init() { 294 if (_ref_processor == NULL) { 295 // Allocate and initialize a reference processor 296 _ref_processor = 297 new ReferenceProcessor(_span, // span 298 (ParallelGCThreads > 1) && ParallelRefProcEnabled, // mt processing 299 (int) ParallelGCThreads, // mt processing degree 300 _cmsGen->refs_discovery_is_mt(), // mt discovery 301 (int) MAX2(ConcGCThreads, ParallelGCThreads), // mt discovery degree 302 _cmsGen->refs_discovery_is_atomic(), // discovery is not atomic 303 &_is_alive_closure); // closure for liveness info 304 // Initialize the _ref_processor field of CMSGen 305 _cmsGen->set_ref_processor(_ref_processor); 306 307 } 308 } 309 310 AdaptiveSizePolicy* CMSCollector::size_policy() { 311 GenCollectedHeap* gch = GenCollectedHeap::heap(); 312 assert(gch->kind() == CollectedHeap::GenCollectedHeap, 313 "Wrong type of heap"); 314 return gch->gen_policy()->size_policy(); 315 } 316 317 void ConcurrentMarkSweepGeneration::initialize_performance_counters() { 318 319 const char* gen_name = "old"; 320 GenCollectorPolicy* gcp = (GenCollectorPolicy*) GenCollectedHeap::heap()->collector_policy(); 321 322 // Generation Counters - generation 1, 1 subspace 323 _gen_counters = new GenerationCounters(gen_name, 1, 1, 324 gcp->min_old_size(), gcp->max_old_size(), &_virtual_space); 325 326 _space_counters = new GSpaceCounters(gen_name, 0, 327 _virtual_space.reserved_size(), 328 this, _gen_counters); 329 } 330 331 CMSStats::CMSStats(ConcurrentMarkSweepGeneration* cms_gen, unsigned int alpha): 332 _cms_gen(cms_gen) 333 { 334 assert(alpha <= 100, "bad value"); 335 _saved_alpha = alpha; 336 337 // Initialize the alphas to the bootstrap value of 100. 338 _gc0_alpha = _cms_alpha = 100; 339 340 _cms_begin_time.update(); 341 _cms_end_time.update(); 342 343 _gc0_duration = 0.0; 344 _gc0_period = 0.0; 345 _gc0_promoted = 0; 346 347 _cms_duration = 0.0; 348 _cms_period = 0.0; 349 _cms_allocated = 0; 350 351 _cms_used_at_gc0_begin = 0; 352 _cms_used_at_gc0_end = 0; 353 _allow_duty_cycle_reduction = false; 354 _valid_bits = 0; 355 } 356 357 double CMSStats::cms_free_adjustment_factor(size_t free) const { 358 // TBD: CR 6909490 359 return 1.0; 360 } 361 362 void CMSStats::adjust_cms_free_adjustment_factor(bool fail, size_t free) { 363 } 364 365 // If promotion failure handling is on use 366 // the padded average size of the promotion for each 367 // young generation collection. 368 double CMSStats::time_until_cms_gen_full() const { 369 size_t cms_free = _cms_gen->cmsSpace()->free(); 370 GenCollectedHeap* gch = GenCollectedHeap::heap(); 371 size_t expected_promotion = MIN2(gch->get_gen(0)->capacity(), 372 (size_t) _cms_gen->gc_stats()->avg_promoted()->padded_average()); 373 if (cms_free > expected_promotion) { 374 // Start a cms collection if there isn't enough space to promote 375 // for the next minor collection. Use the padded average as 376 // a safety factor. 377 cms_free -= expected_promotion; 378 379 // Adjust by the safety factor. 380 double cms_free_dbl = (double)cms_free; 381 double cms_adjustment = (100.0 - CMSIncrementalSafetyFactor)/100.0; 382 // Apply a further correction factor which tries to adjust 383 // for recent occurance of concurrent mode failures. 384 cms_adjustment = cms_adjustment * cms_free_adjustment_factor(cms_free); 385 cms_free_dbl = cms_free_dbl * cms_adjustment; 386 387 if (PrintGCDetails && Verbose) { 388 gclog_or_tty->print_cr("CMSStats::time_until_cms_gen_full: cms_free " 389 SIZE_FORMAT " expected_promotion " SIZE_FORMAT, 390 cms_free, expected_promotion); 391 gclog_or_tty->print_cr(" cms_free_dbl %f cms_consumption_rate %f", 392 cms_free_dbl, cms_consumption_rate() + 1.0); 393 } 394 // Add 1 in case the consumption rate goes to zero. 395 return cms_free_dbl / (cms_consumption_rate() + 1.0); 396 } 397 return 0.0; 398 } 399 400 // Compare the duration of the cms collection to the 401 // time remaining before the cms generation is empty. 402 // Note that the time from the start of the cms collection 403 // to the start of the cms sweep (less than the total 404 // duration of the cms collection) can be used. This 405 // has been tried and some applications experienced 406 // promotion failures early in execution. This was 407 // possibly because the averages were not accurate 408 // enough at the beginning. 409 double CMSStats::time_until_cms_start() const { 410 // We add "gc0_period" to the "work" calculation 411 // below because this query is done (mostly) at the 412 // end of a scavenge, so we need to conservatively 413 // account for that much possible delay 414 // in the query so as to avoid concurrent mode failures 415 // due to starting the collection just a wee bit too 416 // late. 417 double work = cms_duration() + gc0_period(); 418 double deadline = time_until_cms_gen_full(); 419 // If a concurrent mode failure occurred recently, we want to be 420 // more conservative and halve our expected time_until_cms_gen_full() 421 if (work > deadline) { 422 if (Verbose && PrintGCDetails) { 423 gclog_or_tty->print( 424 " CMSCollector: collect because of anticipated promotion " 425 "before full %3.7f + %3.7f > %3.7f ", cms_duration(), 426 gc0_period(), time_until_cms_gen_full()); 427 } 428 return 0.0; 429 } 430 return work - deadline; 431 } 432 433 #ifndef PRODUCT 434 void CMSStats::print_on(outputStream *st) const { 435 st->print(" gc0_alpha=%d,cms_alpha=%d", _gc0_alpha, _cms_alpha); 436 st->print(",gc0_dur=%g,gc0_per=%g,gc0_promo=" SIZE_FORMAT, 437 gc0_duration(), gc0_period(), gc0_promoted()); 438 st->print(",cms_dur=%g,cms_per=%g,cms_alloc=" SIZE_FORMAT, 439 cms_duration(), cms_period(), cms_allocated()); 440 st->print(",cms_since_beg=%g,cms_since_end=%g", 441 cms_time_since_begin(), cms_time_since_end()); 442 st->print(",cms_used_beg=" SIZE_FORMAT ",cms_used_end=" SIZE_FORMAT, 443 _cms_used_at_gc0_begin, _cms_used_at_gc0_end); 444 445 if (valid()) { 446 st->print(",promo_rate=%g,cms_alloc_rate=%g", 447 promotion_rate(), cms_allocation_rate()); 448 st->print(",cms_consumption_rate=%g,time_until_full=%g", 449 cms_consumption_rate(), time_until_cms_gen_full()); 450 } 451 st->print(" "); 452 } 453 #endif // #ifndef PRODUCT 454 455 CMSCollector::CollectorState CMSCollector::_collectorState = 456 CMSCollector::Idling; 457 bool CMSCollector::_foregroundGCIsActive = false; 458 bool CMSCollector::_foregroundGCShouldWait = false; 459 460 CMSCollector::CMSCollector(ConcurrentMarkSweepGeneration* cmsGen, 461 CardTableRS* ct, 462 ConcurrentMarkSweepPolicy* cp): 463 _cmsGen(cmsGen), 464 _ct(ct), 465 _ref_processor(NULL), // will be set later 466 _conc_workers(NULL), // may be set later 467 _abort_preclean(false), 468 _start_sampling(false), 469 _between_prologue_and_epilogue(false), 470 _markBitMap(0, Mutex::leaf + 1, "CMS_markBitMap_lock"), 471 _modUnionTable((CardTableModRefBS::card_shift - LogHeapWordSize), 472 -1 /* lock-free */, "No_lock" /* dummy */), 473 _modUnionClosure(&_modUnionTable), 474 _modUnionClosurePar(&_modUnionTable), 475 // Adjust my span to cover old (cms) gen 476 _span(cmsGen->reserved()), 477 // Construct the is_alive_closure with _span & markBitMap 478 _is_alive_closure(_span, &_markBitMap), 479 _restart_addr(NULL), 480 _overflow_list(NULL), 481 _stats(cmsGen), 482 _eden_chunk_lock(new Mutex(Mutex::leaf + 1, "CMS_eden_chunk_lock", true)), 483 _eden_chunk_array(NULL), // may be set in ctor body 484 _eden_chunk_capacity(0), // -- ditto -- 485 _eden_chunk_index(0), // -- ditto -- 486 _survivor_plab_array(NULL), // -- ditto -- 487 _survivor_chunk_array(NULL), // -- ditto -- 488 _survivor_chunk_capacity(0), // -- ditto -- 489 _survivor_chunk_index(0), // -- ditto -- 490 _ser_pmc_preclean_ovflw(0), 491 _ser_kac_preclean_ovflw(0), 492 _ser_pmc_remark_ovflw(0), 493 _par_pmc_remark_ovflw(0), 494 _ser_kac_ovflw(0), 495 _par_kac_ovflw(0), 496 #ifndef PRODUCT 497 _num_par_pushes(0), 498 #endif 499 _collection_count_start(0), 500 _verifying(false), 501 _verification_mark_bm(0, Mutex::leaf + 1, "CMS_verification_mark_bm_lock"), 502 _completed_initialization(false), 503 _collector_policy(cp), 504 _should_unload_classes(CMSClassUnloadingEnabled), 505 _concurrent_cycles_since_last_unload(0), 506 _roots_scanning_options(SharedHeap::SO_None), 507 _inter_sweep_estimate(CMS_SweepWeight, CMS_SweepPadding), 508 _intra_sweep_estimate(CMS_SweepWeight, CMS_SweepPadding), 509 _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) CMSTracer()), 510 _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()), 511 _cms_start_registered(false) 512 { 513 if (ExplicitGCInvokesConcurrentAndUnloadsClasses) { 514 ExplicitGCInvokesConcurrent = true; 515 } 516 // Now expand the span and allocate the collection support structures 517 // (MUT, marking bit map etc.) to cover both generations subject to 518 // collection. 519 520 // For use by dirty card to oop closures. 521 _cmsGen->cmsSpace()->set_collector(this); 522 523 // Allocate MUT and marking bit map 524 { 525 MutexLockerEx x(_markBitMap.lock(), Mutex::_no_safepoint_check_flag); 526 if (!_markBitMap.allocate(_span)) { 527 warning("Failed to allocate CMS Bit Map"); 528 return; 529 } 530 assert(_markBitMap.covers(_span), "_markBitMap inconsistency?"); 531 } 532 { 533 _modUnionTable.allocate(_span); 534 assert(_modUnionTable.covers(_span), "_modUnionTable inconsistency?"); 535 } 536 537 if (!_markStack.allocate(MarkStackSize)) { 538 warning("Failed to allocate CMS Marking Stack"); 539 return; 540 } 541 542 // Support for multi-threaded concurrent phases 543 if (CMSConcurrentMTEnabled) { 544 if (FLAG_IS_DEFAULT(ConcGCThreads)) { 545 // just for now 546 FLAG_SET_DEFAULT(ConcGCThreads, (ParallelGCThreads + 3)/4); 547 } 548 if (ConcGCThreads > 1) { 549 _conc_workers = new YieldingFlexibleWorkGang("Parallel CMS Threads", 550 ConcGCThreads, true); 551 if (_conc_workers == NULL) { 552 warning("GC/CMS: _conc_workers allocation failure: " 553 "forcing -CMSConcurrentMTEnabled"); 554 CMSConcurrentMTEnabled = false; 555 } else { 556 _conc_workers->initialize_workers(); 557 } 558 } else { 559 CMSConcurrentMTEnabled = false; 560 } 561 } 562 if (!CMSConcurrentMTEnabled) { 563 ConcGCThreads = 0; 564 } else { 565 // Turn off CMSCleanOnEnter optimization temporarily for 566 // the MT case where it's not fixed yet; see 6178663. 567 CMSCleanOnEnter = false; 568 } 569 assert((_conc_workers != NULL) == (ConcGCThreads > 1), 570 "Inconsistency"); 571 572 // Parallel task queues; these are shared for the 573 // concurrent and stop-world phases of CMS, but 574 // are not shared with parallel scavenge (ParNew). 575 { 576 uint i; 577 uint num_queues = (uint) MAX2(ParallelGCThreads, ConcGCThreads); 578 579 if ((CMSParallelRemarkEnabled || CMSConcurrentMTEnabled 580 || ParallelRefProcEnabled) 581 && num_queues > 0) { 582 _task_queues = new OopTaskQueueSet(num_queues); 583 if (_task_queues == NULL) { 584 warning("task_queues allocation failure."); 585 return; 586 } 587 _hash_seed = NEW_C_HEAP_ARRAY(int, num_queues, mtGC); 588 if (_hash_seed == NULL) { 589 warning("_hash_seed array allocation failure"); 590 return; 591 } 592 593 typedef Padded<OopTaskQueue> PaddedOopTaskQueue; 594 for (i = 0; i < num_queues; i++) { 595 PaddedOopTaskQueue *q = new PaddedOopTaskQueue(); 596 if (q == NULL) { 597 warning("work_queue allocation failure."); 598 return; 599 } 600 _task_queues->register_queue(i, q); 601 } 602 for (i = 0; i < num_queues; i++) { 603 _task_queues->queue(i)->initialize(); 604 _hash_seed[i] = 17; // copied from ParNew 605 } 606 } 607 } 608 609 _cmsGen ->init_initiating_occupancy(CMSInitiatingOccupancyFraction, CMSTriggerRatio); 610 611 // Clip CMSBootstrapOccupancy between 0 and 100. 612 _bootstrap_occupancy = ((double)CMSBootstrapOccupancy)/(double)100; 613 614 // Now tell CMS generations the identity of their collector 615 ConcurrentMarkSweepGeneration::set_collector(this); 616 617 // Create & start a CMS thread for this CMS collector 618 _cmsThread = ConcurrentMarkSweepThread::start(this); 619 assert(cmsThread() != NULL, "CMS Thread should have been created"); 620 assert(cmsThread()->collector() == this, 621 "CMS Thread should refer to this gen"); 622 assert(CGC_lock != NULL, "Where's the CGC_lock?"); 623 624 // Support for parallelizing young gen rescan 625 GenCollectedHeap* gch = GenCollectedHeap::heap(); 626 _young_gen = gch->prev_gen(_cmsGen); 627 if (gch->supports_inline_contig_alloc()) { 628 _top_addr = gch->top_addr(); 629 _end_addr = gch->end_addr(); 630 assert(_young_gen != NULL, "no _young_gen"); 631 _eden_chunk_index = 0; 632 _eden_chunk_capacity = (_young_gen->max_capacity()+CMSSamplingGrain)/CMSSamplingGrain; 633 _eden_chunk_array = NEW_C_HEAP_ARRAY(HeapWord*, _eden_chunk_capacity, mtGC); 634 if (_eden_chunk_array == NULL) { 635 _eden_chunk_capacity = 0; 636 warning("GC/CMS: _eden_chunk_array allocation failure"); 637 } 638 } 639 assert(_eden_chunk_array != NULL || _eden_chunk_capacity == 0, "Error"); 640 641 // Support for parallelizing survivor space rescan 642 if ((CMSParallelRemarkEnabled && CMSParallelSurvivorRemarkEnabled) || CMSParallelInitialMarkEnabled) { 643 const size_t max_plab_samples = 644 ((DefNewGeneration*)_young_gen)->max_survivor_size()/MinTLABSize; 645 646 _survivor_plab_array = NEW_C_HEAP_ARRAY(ChunkArray, ParallelGCThreads, mtGC); 647 _survivor_chunk_array = NEW_C_HEAP_ARRAY(HeapWord*, 2*max_plab_samples, mtGC); 648 _cursor = NEW_C_HEAP_ARRAY(size_t, ParallelGCThreads, mtGC); 649 if (_survivor_plab_array == NULL || _survivor_chunk_array == NULL 650 || _cursor == NULL) { 651 warning("Failed to allocate survivor plab/chunk array"); 652 if (_survivor_plab_array != NULL) { 653 FREE_C_HEAP_ARRAY(ChunkArray, _survivor_plab_array, mtGC); 654 _survivor_plab_array = NULL; 655 } 656 if (_survivor_chunk_array != NULL) { 657 FREE_C_HEAP_ARRAY(HeapWord*, _survivor_chunk_array, mtGC); 658 _survivor_chunk_array = NULL; 659 } 660 if (_cursor != NULL) { 661 FREE_C_HEAP_ARRAY(size_t, _cursor, mtGC); 662 _cursor = NULL; 663 } 664 } else { 665 _survivor_chunk_capacity = 2*max_plab_samples; 666 for (uint i = 0; i < ParallelGCThreads; i++) { 667 HeapWord** vec = NEW_C_HEAP_ARRAY(HeapWord*, max_plab_samples, mtGC); 668 if (vec == NULL) { 669 warning("Failed to allocate survivor plab array"); 670 for (int j = i; j > 0; j--) { 671 FREE_C_HEAP_ARRAY(HeapWord*, _survivor_plab_array[j-1].array(), mtGC); 672 } 673 FREE_C_HEAP_ARRAY(ChunkArray, _survivor_plab_array, mtGC); 674 FREE_C_HEAP_ARRAY(HeapWord*, _survivor_chunk_array, mtGC); 675 _survivor_plab_array = NULL; 676 _survivor_chunk_array = NULL; 677 _survivor_chunk_capacity = 0; 678 break; 679 } else { 680 ChunkArray* cur = 681 ::new (&_survivor_plab_array[i]) ChunkArray(vec, 682 max_plab_samples); 683 assert(cur->end() == 0, "Should be 0"); 684 assert(cur->array() == vec, "Should be vec"); 685 assert(cur->capacity() == max_plab_samples, "Error"); 686 } 687 } 688 } 689 } 690 assert( ( _survivor_plab_array != NULL 691 && _survivor_chunk_array != NULL) 692 || ( _survivor_chunk_capacity == 0 693 && _survivor_chunk_index == 0), 694 "Error"); 695 696 NOT_PRODUCT(_overflow_counter = CMSMarkStackOverflowInterval;) 697 _gc_counters = new CollectorCounters("CMS", 1); 698 _completed_initialization = true; 699 _inter_sweep_timer.start(); // start of time 700 } 701 702 const char* ConcurrentMarkSweepGeneration::name() const { 703 return "concurrent mark-sweep generation"; 704 } 705 void ConcurrentMarkSweepGeneration::update_counters() { 706 if (UsePerfData) { 707 _space_counters->update_all(); 708 _gen_counters->update_all(); 709 } 710 } 711 712 // this is an optimized version of update_counters(). it takes the 713 // used value as a parameter rather than computing it. 714 // 715 void ConcurrentMarkSweepGeneration::update_counters(size_t used) { 716 if (UsePerfData) { 717 _space_counters->update_used(used); 718 _space_counters->update_capacity(); 719 _gen_counters->update_all(); 720 } 721 } 722 723 void ConcurrentMarkSweepGeneration::print() const { 724 Generation::print(); 725 cmsSpace()->print(); 726 } 727 728 #ifndef PRODUCT 729 void ConcurrentMarkSweepGeneration::print_statistics() { 730 cmsSpace()->printFLCensus(0); 731 } 732 #endif 733 734 void ConcurrentMarkSweepGeneration::printOccupancy(const char *s) { 735 GenCollectedHeap* gch = GenCollectedHeap::heap(); 736 if (PrintGCDetails) { 737 if (Verbose) { 738 gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"("SIZE_FORMAT")]", 739 level(), short_name(), s, used(), capacity()); 740 } else { 741 gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"K("SIZE_FORMAT"K)]", 742 level(), short_name(), s, used() / K, capacity() / K); 743 } 744 } 745 if (Verbose) { 746 gclog_or_tty->print(" "SIZE_FORMAT"("SIZE_FORMAT")", 747 gch->used(), gch->capacity()); 748 } else { 749 gclog_or_tty->print(" "SIZE_FORMAT"K("SIZE_FORMAT"K)", 750 gch->used() / K, gch->capacity() / K); 751 } 752 } 753 754 size_t 755 ConcurrentMarkSweepGeneration::contiguous_available() const { 756 // dld proposes an improvement in precision here. If the committed 757 // part of the space ends in a free block we should add that to 758 // uncommitted size in the calculation below. Will make this 759 // change later, staying with the approximation below for the 760 // time being. -- ysr. 761 return MAX2(_virtual_space.uncommitted_size(), unsafe_max_alloc_nogc()); 762 } 763 764 size_t 765 ConcurrentMarkSweepGeneration::unsafe_max_alloc_nogc() const { 766 return _cmsSpace->max_alloc_in_words() * HeapWordSize; 767 } 768 769 size_t ConcurrentMarkSweepGeneration::max_available() const { 770 return free() + _virtual_space.uncommitted_size(); 771 } 772 773 bool ConcurrentMarkSweepGeneration::promotion_attempt_is_safe(size_t max_promotion_in_bytes) const { 774 size_t available = max_available(); 775 size_t av_promo = (size_t)gc_stats()->avg_promoted()->padded_average(); 776 bool res = (available >= av_promo) || (available >= max_promotion_in_bytes); 777 if (Verbose && PrintGCDetails) { 778 gclog_or_tty->print_cr( 779 "CMS: promo attempt is%s safe: available("SIZE_FORMAT") %s av_promo("SIZE_FORMAT")," 780 "max_promo("SIZE_FORMAT")", 781 res? "":" not", available, res? ">=":"<", 782 av_promo, max_promotion_in_bytes); 783 } 784 return res; 785 } 786 787 // At a promotion failure dump information on block layout in heap 788 // (cms old generation). 789 void ConcurrentMarkSweepGeneration::promotion_failure_occurred() { 790 if (CMSDumpAtPromotionFailure) { 791 cmsSpace()->dump_at_safepoint_with_locks(collector(), gclog_or_tty); 792 } 793 } 794 795 CompactibleSpace* 796 ConcurrentMarkSweepGeneration::first_compaction_space() const { 797 return _cmsSpace; 798 } 799 800 void ConcurrentMarkSweepGeneration::reset_after_compaction() { 801 // Clear the promotion information. These pointers can be adjusted 802 // along with all the other pointers into the heap but 803 // compaction is expected to be a rare event with 804 // a heap using cms so don't do it without seeing the need. 805 for (uint i = 0; i < ParallelGCThreads; i++) { 806 _par_gc_thread_states[i]->promo.reset(); 807 } 808 } 809 810 void ConcurrentMarkSweepGeneration::space_iterate(SpaceClosure* blk, bool usedOnly) { 811 blk->do_space(_cmsSpace); 812 } 813 814 void ConcurrentMarkSweepGeneration::compute_new_size() { 815 assert_locked_or_safepoint(Heap_lock); 816 817 // If incremental collection failed, we just want to expand 818 // to the limit. 819 if (incremental_collection_failed()) { 820 clear_incremental_collection_failed(); 821 grow_to_reserved(); 822 return; 823 } 824 825 // The heap has been compacted but not reset yet. 826 // Any metric such as free() or used() will be incorrect. 827 828 CardGeneration::compute_new_size(); 829 830 // Reset again after a possible resizing 831 if (did_compact()) { 832 cmsSpace()->reset_after_compaction(); 833 } 834 } 835 836 void ConcurrentMarkSweepGeneration::compute_new_size_free_list() { 837 assert_locked_or_safepoint(Heap_lock); 838 839 // If incremental collection failed, we just want to expand 840 // to the limit. 841 if (incremental_collection_failed()) { 842 clear_incremental_collection_failed(); 843 grow_to_reserved(); 844 return; 845 } 846 847 double free_percentage = ((double) free()) / capacity(); 848 double desired_free_percentage = (double) MinHeapFreeRatio / 100; 849 double maximum_free_percentage = (double) MaxHeapFreeRatio / 100; 850 851 // compute expansion delta needed for reaching desired free percentage 852 if (free_percentage < desired_free_percentage) { 853 size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage)); 854 assert(desired_capacity >= capacity(), "invalid expansion size"); 855 size_t expand_bytes = MAX2(desired_capacity - capacity(), MinHeapDeltaBytes); 856 if (PrintGCDetails && Verbose) { 857 size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage)); 858 gclog_or_tty->print_cr("\nFrom compute_new_size: "); 859 gclog_or_tty->print_cr(" Free fraction %f", free_percentage); 860 gclog_or_tty->print_cr(" Desired free fraction %f", 861 desired_free_percentage); 862 gclog_or_tty->print_cr(" Maximum free fraction %f", 863 maximum_free_percentage); 864 gclog_or_tty->print_cr(" Capacity "SIZE_FORMAT, capacity()/1000); 865 gclog_or_tty->print_cr(" Desired capacity "SIZE_FORMAT, 866 desired_capacity/1000); 867 int prev_level = level() - 1; 868 if (prev_level >= 0) { 869 size_t prev_size = 0; 870 GenCollectedHeap* gch = GenCollectedHeap::heap(); 871 Generation* prev_gen = gch->_gens[prev_level]; 872 prev_size = prev_gen->capacity(); 873 gclog_or_tty->print_cr(" Younger gen size "SIZE_FORMAT, 874 prev_size/1000); 875 } 876 gclog_or_tty->print_cr(" unsafe_max_alloc_nogc "SIZE_FORMAT, 877 unsafe_max_alloc_nogc()/1000); 878 gclog_or_tty->print_cr(" contiguous available "SIZE_FORMAT, 879 contiguous_available()/1000); 880 gclog_or_tty->print_cr(" Expand by "SIZE_FORMAT" (bytes)", 881 expand_bytes); 882 } 883 // safe if expansion fails 884 expand(expand_bytes, 0, CMSExpansionCause::_satisfy_free_ratio); 885 if (PrintGCDetails && Verbose) { 886 gclog_or_tty->print_cr(" Expanded free fraction %f", 887 ((double) free()) / capacity()); 888 } 889 } else { 890 size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage)); 891 assert(desired_capacity <= capacity(), "invalid expansion size"); 892 size_t shrink_bytes = capacity() - desired_capacity; 893 // Don't shrink unless the delta is greater than the minimum shrink we want 894 if (shrink_bytes >= MinHeapDeltaBytes) { 895 shrink_free_list_by(shrink_bytes); 896 } 897 } 898 } 899 900 Mutex* ConcurrentMarkSweepGeneration::freelistLock() const { 901 return cmsSpace()->freelistLock(); 902 } 903 904 HeapWord* ConcurrentMarkSweepGeneration::allocate(size_t size, 905 bool tlab) { 906 CMSSynchronousYieldRequest yr; 907 MutexLockerEx x(freelistLock(), 908 Mutex::_no_safepoint_check_flag); 909 return have_lock_and_allocate(size, tlab); 910 } 911 912 HeapWord* ConcurrentMarkSweepGeneration::have_lock_and_allocate(size_t size, 913 bool tlab /* ignored */) { 914 assert_lock_strong(freelistLock()); 915 size_t adjustedSize = CompactibleFreeListSpace::adjustObjectSize(size); 916 HeapWord* res = cmsSpace()->allocate(adjustedSize); 917 // Allocate the object live (grey) if the background collector has 918 // started marking. This is necessary because the marker may 919 // have passed this address and consequently this object will 920 // not otherwise be greyed and would be incorrectly swept up. 921 // Note that if this object contains references, the writing 922 // of those references will dirty the card containing this object 923 // allowing the object to be blackened (and its references scanned) 924 // either during a preclean phase or at the final checkpoint. 925 if (res != NULL) { 926 // We may block here with an uninitialized object with 927 // its mark-bit or P-bits not yet set. Such objects need 928 // to be safely navigable by block_start(). 929 assert(oop(res)->klass_or_null() == NULL, "Object should be uninitialized here."); 930 assert(!((FreeChunk*)res)->is_free(), "Error, block will look free but show wrong size"); 931 collector()->direct_allocated(res, adjustedSize); 932 _direct_allocated_words += adjustedSize; 933 // allocation counters 934 NOT_PRODUCT( 935 _numObjectsAllocated++; 936 _numWordsAllocated += (int)adjustedSize; 937 ) 938 } 939 return res; 940 } 941 942 // In the case of direct allocation by mutators in a generation that 943 // is being concurrently collected, the object must be allocated 944 // live (grey) if the background collector has started marking. 945 // This is necessary because the marker may 946 // have passed this address and consequently this object will 947 // not otherwise be greyed and would be incorrectly swept up. 948 // Note that if this object contains references, the writing 949 // of those references will dirty the card containing this object 950 // allowing the object to be blackened (and its references scanned) 951 // either during a preclean phase or at the final checkpoint. 952 void CMSCollector::direct_allocated(HeapWord* start, size_t size) { 953 assert(_markBitMap.covers(start, size), "Out of bounds"); 954 if (_collectorState >= Marking) { 955 MutexLockerEx y(_markBitMap.lock(), 956 Mutex::_no_safepoint_check_flag); 957 // [see comments preceding SweepClosure::do_blk() below for details] 958 // 959 // Can the P-bits be deleted now? JJJ 960 // 961 // 1. need to mark the object as live so it isn't collected 962 // 2. need to mark the 2nd bit to indicate the object may be uninitialized 963 // 3. need to mark the end of the object so marking, precleaning or sweeping 964 // can skip over uninitialized or unparsable objects. An allocated 965 // object is considered uninitialized for our purposes as long as 966 // its klass word is NULL. All old gen objects are parsable 967 // as soon as they are initialized.) 968 _markBitMap.mark(start); // object is live 969 _markBitMap.mark(start + 1); // object is potentially uninitialized? 970 _markBitMap.mark(start + size - 1); 971 // mark end of object 972 } 973 // check that oop looks uninitialized 974 assert(oop(start)->klass_or_null() == NULL, "_klass should be NULL"); 975 } 976 977 void CMSCollector::promoted(bool par, HeapWord* start, 978 bool is_obj_array, size_t obj_size) { 979 assert(_markBitMap.covers(start), "Out of bounds"); 980 // See comment in direct_allocated() about when objects should 981 // be allocated live. 982 if (_collectorState >= Marking) { 983 // we already hold the marking bit map lock, taken in 984 // the prologue 985 if (par) { 986 _markBitMap.par_mark(start); 987 } else { 988 _markBitMap.mark(start); 989 } 990 // We don't need to mark the object as uninitialized (as 991 // in direct_allocated above) because this is being done with the 992 // world stopped and the object will be initialized by the 993 // time the marking, precleaning or sweeping get to look at it. 994 // But see the code for copying objects into the CMS generation, 995 // where we need to ensure that concurrent readers of the 996 // block offset table are able to safely navigate a block that 997 // is in flux from being free to being allocated (and in 998 // transition while being copied into) and subsequently 999 // becoming a bona-fide object when the copy/promotion is complete. 1000 assert(SafepointSynchronize::is_at_safepoint(), 1001 "expect promotion only at safepoints"); 1002 1003 if (_collectorState < Sweeping) { 1004 // Mark the appropriate cards in the modUnionTable, so that 1005 // this object gets scanned before the sweep. If this is 1006 // not done, CMS generation references in the object might 1007 // not get marked. 1008 // For the case of arrays, which are otherwise precisely 1009 // marked, we need to dirty the entire array, not just its head. 1010 if (is_obj_array) { 1011 // The [par_]mark_range() method expects mr.end() below to 1012 // be aligned to the granularity of a bit's representation 1013 // in the heap. In the case of the MUT below, that's a 1014 // card size. 1015 MemRegion mr(start, 1016 (HeapWord*)round_to((intptr_t)(start + obj_size), 1017 CardTableModRefBS::card_size /* bytes */)); 1018 if (par) { 1019 _modUnionTable.par_mark_range(mr); 1020 } else { 1021 _modUnionTable.mark_range(mr); 1022 } 1023 } else { // not an obj array; we can just mark the head 1024 if (par) { 1025 _modUnionTable.par_mark(start); 1026 } else { 1027 _modUnionTable.mark(start); 1028 } 1029 } 1030 } 1031 } 1032 } 1033 1034 oop ConcurrentMarkSweepGeneration::promote(oop obj, size_t obj_size) { 1035 assert(obj_size == (size_t)obj->size(), "bad obj_size passed in"); 1036 // allocate, copy and if necessary update promoinfo -- 1037 // delegate to underlying space. 1038 assert_lock_strong(freelistLock()); 1039 1040 #ifndef PRODUCT 1041 if (Universe::heap()->promotion_should_fail()) { 1042 return NULL; 1043 } 1044 #endif // #ifndef PRODUCT 1045 1046 oop res = _cmsSpace->promote(obj, obj_size); 1047 if (res == NULL) { 1048 // expand and retry 1049 size_t s = _cmsSpace->expansionSpaceRequired(obj_size); // HeapWords 1050 expand(s*HeapWordSize, MinHeapDeltaBytes, 1051 CMSExpansionCause::_satisfy_promotion); 1052 // Since there's currently no next generation, we don't try to promote 1053 // into a more senior generation. 1054 assert(next_gen() == NULL, "assumption, based upon which no attempt " 1055 "is made to pass on a possibly failing " 1056 "promotion to next generation"); 1057 res = _cmsSpace->promote(obj, obj_size); 1058 } 1059 if (res != NULL) { 1060 // See comment in allocate() about when objects should 1061 // be allocated live. 1062 assert(obj->is_oop(), "Will dereference klass pointer below"); 1063 collector()->promoted(false, // Not parallel 1064 (HeapWord*)res, obj->is_objArray(), obj_size); 1065 // promotion counters 1066 NOT_PRODUCT( 1067 _numObjectsPromoted++; 1068 _numWordsPromoted += 1069 (int)(CompactibleFreeListSpace::adjustObjectSize(obj->size())); 1070 ) 1071 } 1072 return res; 1073 } 1074 1075 1076 // IMPORTANT: Notes on object size recognition in CMS. 1077 // --------------------------------------------------- 1078 // A block of storage in the CMS generation is always in 1079 // one of three states. A free block (FREE), an allocated 1080 // object (OBJECT) whose size() method reports the correct size, 1081 // and an intermediate state (TRANSIENT) in which its size cannot 1082 // be accurately determined. 1083 // STATE IDENTIFICATION: (32 bit and 64 bit w/o COOPS) 1084 // ----------------------------------------------------- 1085 // FREE: klass_word & 1 == 1; mark_word holds block size 1086 // 1087 // OBJECT: klass_word installed; klass_word != 0 && klass_word & 1 == 0; 1088 // obj->size() computes correct size 1089 // 1090 // TRANSIENT: klass_word == 0; size is indeterminate until we become an OBJECT 1091 // 1092 // STATE IDENTIFICATION: (64 bit+COOPS) 1093 // ------------------------------------ 1094 // FREE: mark_word & CMS_FREE_BIT == 1; mark_word & ~CMS_FREE_BIT gives block_size 1095 // 1096 // OBJECT: klass_word installed; klass_word != 0; 1097 // obj->size() computes correct size 1098 // 1099 // TRANSIENT: klass_word == 0; size is indeterminate until we become an OBJECT 1100 // 1101 // 1102 // STATE TRANSITION DIAGRAM 1103 // 1104 // mut / parnew mut / parnew 1105 // FREE --------------------> TRANSIENT ---------------------> OBJECT --| 1106 // ^ | 1107 // |------------------------ DEAD <------------------------------------| 1108 // sweep mut 1109 // 1110 // While a block is in TRANSIENT state its size cannot be determined 1111 // so readers will either need to come back later or stall until 1112 // the size can be determined. Note that for the case of direct 1113 // allocation, P-bits, when available, may be used to determine the 1114 // size of an object that may not yet have been initialized. 1115 1116 // Things to support parallel young-gen collection. 1117 oop 1118 ConcurrentMarkSweepGeneration::par_promote(int thread_num, 1119 oop old, markOop m, 1120 size_t word_sz) { 1121 #ifndef PRODUCT 1122 if (Universe::heap()->promotion_should_fail()) { 1123 return NULL; 1124 } 1125 #endif // #ifndef PRODUCT 1126 1127 CMSParGCThreadState* ps = _par_gc_thread_states[thread_num]; 1128 PromotionInfo* promoInfo = &ps->promo; 1129 // if we are tracking promotions, then first ensure space for 1130 // promotion (including spooling space for saving header if necessary). 1131 // then allocate and copy, then track promoted info if needed. 1132 // When tracking (see PromotionInfo::track()), the mark word may 1133 // be displaced and in this case restoration of the mark word 1134 // occurs in the (oop_since_save_marks_)iterate phase. 1135 if (promoInfo->tracking() && !promoInfo->ensure_spooling_space()) { 1136 // Out of space for allocating spooling buffers; 1137 // try expanding and allocating spooling buffers. 1138 if (!expand_and_ensure_spooling_space(promoInfo)) { 1139 return NULL; 1140 } 1141 } 1142 assert(promoInfo->has_spooling_space(), "Control point invariant"); 1143 const size_t alloc_sz = CompactibleFreeListSpace::adjustObjectSize(word_sz); 1144 HeapWord* obj_ptr = ps->lab.alloc(alloc_sz); 1145 if (obj_ptr == NULL) { 1146 obj_ptr = expand_and_par_lab_allocate(ps, alloc_sz); 1147 if (obj_ptr == NULL) { 1148 return NULL; 1149 } 1150 } 1151 oop obj = oop(obj_ptr); 1152 OrderAccess::storestore(); 1153 assert(obj->klass_or_null() == NULL, "Object should be uninitialized here."); 1154 assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size"); 1155 // IMPORTANT: See note on object initialization for CMS above. 1156 // Otherwise, copy the object. Here we must be careful to insert the 1157 // klass pointer last, since this marks the block as an allocated object. 1158 // Except with compressed oops it's the mark word. 1159 HeapWord* old_ptr = (HeapWord*)old; 1160 // Restore the mark word copied above. 1161 obj->set_mark(m); 1162 assert(obj->klass_or_null() == NULL, "Object should be uninitialized here."); 1163 assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size"); 1164 OrderAccess::storestore(); 1165 1166 if (UseCompressedClassPointers) { 1167 // Copy gap missed by (aligned) header size calculation below 1168 obj->set_klass_gap(old->klass_gap()); 1169 } 1170 if (word_sz > (size_t)oopDesc::header_size()) { 1171 Copy::aligned_disjoint_words(old_ptr + oopDesc::header_size(), 1172 obj_ptr + oopDesc::header_size(), 1173 word_sz - oopDesc::header_size()); 1174 } 1175 1176 // Now we can track the promoted object, if necessary. We take care 1177 // to delay the transition from uninitialized to full object 1178 // (i.e., insertion of klass pointer) until after, so that it 1179 // atomically becomes a promoted object. 1180 if (promoInfo->tracking()) { 1181 promoInfo->track((PromotedObject*)obj, old->klass()); 1182 } 1183 assert(obj->klass_or_null() == NULL, "Object should be uninitialized here."); 1184 assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size"); 1185 assert(old->is_oop(), "Will use and dereference old klass ptr below"); 1186 1187 // Finally, install the klass pointer (this should be volatile). 1188 OrderAccess::storestore(); 1189 obj->set_klass(old->klass()); 1190 // We should now be able to calculate the right size for this object 1191 assert(obj->is_oop() && obj->size() == (int)word_sz, "Error, incorrect size computed for promoted object"); 1192 1193 collector()->promoted(true, // parallel 1194 obj_ptr, old->is_objArray(), word_sz); 1195 1196 NOT_PRODUCT( 1197 Atomic::inc_ptr(&_numObjectsPromoted); 1198 Atomic::add_ptr(alloc_sz, &_numWordsPromoted); 1199 ) 1200 1201 return obj; 1202 } 1203 1204 void 1205 ConcurrentMarkSweepGeneration:: 1206 par_promote_alloc_done(int thread_num) { 1207 CMSParGCThreadState* ps = _par_gc_thread_states[thread_num]; 1208 ps->lab.retire(thread_num); 1209 } 1210 1211 void 1212 ConcurrentMarkSweepGeneration:: 1213 par_oop_since_save_marks_iterate_done(int thread_num) { 1214 CMSParGCThreadState* ps = _par_gc_thread_states[thread_num]; 1215 ParScanWithoutBarrierClosure* dummy_cl = NULL; 1216 ps->promo.promoted_oops_iterate_nv(dummy_cl); 1217 } 1218 1219 bool ConcurrentMarkSweepGeneration::should_collect(bool full, 1220 size_t size, 1221 bool tlab) 1222 { 1223 // We allow a STW collection only if a full 1224 // collection was requested. 1225 return full || should_allocate(size, tlab); // FIX ME !!! 1226 // This and promotion failure handling are connected at the 1227 // hip and should be fixed by untying them. 1228 } 1229 1230 bool CMSCollector::shouldConcurrentCollect() { 1231 if (_full_gc_requested) { 1232 if (Verbose && PrintGCDetails) { 1233 gclog_or_tty->print_cr("CMSCollector: collect because of explicit " 1234 " gc request (or gc_locker)"); 1235 } 1236 return true; 1237 } 1238 1239 FreelistLocker x(this); 1240 // ------------------------------------------------------------------ 1241 // Print out lots of information which affects the initiation of 1242 // a collection. 1243 if (PrintCMSInitiationStatistics && stats().valid()) { 1244 gclog_or_tty->print("CMSCollector shouldConcurrentCollect: "); 1245 gclog_or_tty->stamp(); 1246 gclog_or_tty->cr(); 1247 stats().print_on(gclog_or_tty); 1248 gclog_or_tty->print_cr("time_until_cms_gen_full %3.7f", 1249 stats().time_until_cms_gen_full()); 1250 gclog_or_tty->print_cr("free="SIZE_FORMAT, _cmsGen->free()); 1251 gclog_or_tty->print_cr("contiguous_available="SIZE_FORMAT, 1252 _cmsGen->contiguous_available()); 1253 gclog_or_tty->print_cr("promotion_rate=%g", stats().promotion_rate()); 1254 gclog_or_tty->print_cr("cms_allocation_rate=%g", stats().cms_allocation_rate()); 1255 gclog_or_tty->print_cr("occupancy=%3.7f", _cmsGen->occupancy()); 1256 gclog_or_tty->print_cr("initiatingOccupancy=%3.7f", _cmsGen->initiating_occupancy()); 1257 gclog_or_tty->print_cr("cms_time_since_begin=%3.7f", stats().cms_time_since_begin()); 1258 gclog_or_tty->print_cr("cms_time_since_end=%3.7f", stats().cms_time_since_end()); 1259 gclog_or_tty->print_cr("metadata initialized %d", 1260 MetaspaceGC::should_concurrent_collect()); 1261 } 1262 // ------------------------------------------------------------------ 1263 1264 // If the estimated time to complete a cms collection (cms_duration()) 1265 // is less than the estimated time remaining until the cms generation 1266 // is full, start a collection. 1267 if (!UseCMSInitiatingOccupancyOnly) { 1268 if (stats().valid()) { 1269 if (stats().time_until_cms_start() == 0.0) { 1270 return true; 1271 } 1272 } else { 1273 // We want to conservatively collect somewhat early in order 1274 // to try and "bootstrap" our CMS/promotion statistics; 1275 // this branch will not fire after the first successful CMS 1276 // collection because the stats should then be valid. 1277 if (_cmsGen->occupancy() >= _bootstrap_occupancy) { 1278 if (Verbose && PrintGCDetails) { 1279 gclog_or_tty->print_cr( 1280 " CMSCollector: collect for bootstrapping statistics:" 1281 " occupancy = %f, boot occupancy = %f", _cmsGen->occupancy(), 1282 _bootstrap_occupancy); 1283 } 1284 return true; 1285 } 1286 } 1287 } 1288 1289 // Otherwise, we start a collection cycle if 1290 // old gen want a collection cycle started. Each may use 1291 // an appropriate criterion for making this decision. 1292 // XXX We need to make sure that the gen expansion 1293 // criterion dovetails well with this. XXX NEED TO FIX THIS 1294 if (_cmsGen->should_concurrent_collect()) { 1295 if (Verbose && PrintGCDetails) { 1296 gclog_or_tty->print_cr("CMS old gen initiated"); 1297 } 1298 return true; 1299 } 1300 1301 // We start a collection if we believe an incremental collection may fail; 1302 // this is not likely to be productive in practice because it's probably too 1303 // late anyway. 1304 GenCollectedHeap* gch = GenCollectedHeap::heap(); 1305 assert(gch->collector_policy()->is_generation_policy(), 1306 "You may want to check the correctness of the following"); 1307 if (gch->incremental_collection_will_fail(true /* consult_young */)) { 1308 if (Verbose && PrintGCDetails) { 1309 gclog_or_tty->print("CMSCollector: collect because incremental collection will fail "); 1310 } 1311 return true; 1312 } 1313 1314 if (MetaspaceGC::should_concurrent_collect()) { 1315 if (Verbose && PrintGCDetails) { 1316 gclog_or_tty->print("CMSCollector: collect for metadata allocation "); 1317 } 1318 return true; 1319 } 1320 1321 // CMSTriggerInterval starts a CMS cycle if enough time has passed. 1322 if (CMSTriggerInterval >= 0) { 1323 if (CMSTriggerInterval == 0) { 1324 // Trigger always 1325 return true; 1326 } 1327 1328 // Check the CMS time since begin (we do not check the stats validity 1329 // as we want to be able to trigger the first CMS cycle as well) 1330 if (stats().cms_time_since_begin() >= (CMSTriggerInterval / ((double) MILLIUNITS))) { 1331 if (Verbose && PrintGCDetails) { 1332 if (stats().valid()) { 1333 gclog_or_tty->print_cr("CMSCollector: collect because of trigger interval (time since last begin %3.7f secs)", 1334 stats().cms_time_since_begin()); 1335 } else { 1336 gclog_or_tty->print_cr("CMSCollector: collect because of trigger interval (first collection)"); 1337 } 1338 } 1339 return true; 1340 } 1341 } 1342 1343 return false; 1344 } 1345 1346 void CMSCollector::set_did_compact(bool v) { _cmsGen->set_did_compact(v); } 1347 1348 // Clear _expansion_cause fields of constituent generations 1349 void CMSCollector::clear_expansion_cause() { 1350 _cmsGen->clear_expansion_cause(); 1351 } 1352 1353 // We should be conservative in starting a collection cycle. To 1354 // start too eagerly runs the risk of collecting too often in the 1355 // extreme. To collect too rarely falls back on full collections, 1356 // which works, even if not optimum in terms of concurrent work. 1357 // As a work around for too eagerly collecting, use the flag 1358 // UseCMSInitiatingOccupancyOnly. This also has the advantage of 1359 // giving the user an easily understandable way of controlling the 1360 // collections. 1361 // We want to start a new collection cycle if any of the following 1362 // conditions hold: 1363 // . our current occupancy exceeds the configured initiating occupancy 1364 // for this generation, or 1365 // . we recently needed to expand this space and have not, since that 1366 // expansion, done a collection of this generation, or 1367 // . the underlying space believes that it may be a good idea to initiate 1368 // a concurrent collection (this may be based on criteria such as the 1369 // following: the space uses linear allocation and linear allocation is 1370 // going to fail, or there is believed to be excessive fragmentation in 1371 // the generation, etc... or ... 1372 // [.(currently done by CMSCollector::shouldConcurrentCollect() only for 1373 // the case of the old generation; see CR 6543076): 1374 // we may be approaching a point at which allocation requests may fail because 1375 // we will be out of sufficient free space given allocation rate estimates.] 1376 bool ConcurrentMarkSweepGeneration::should_concurrent_collect() const { 1377 1378 assert_lock_strong(freelistLock()); 1379 if (occupancy() > initiating_occupancy()) { 1380 if (PrintGCDetails && Verbose) { 1381 gclog_or_tty->print(" %s: collect because of occupancy %f / %f ", 1382 short_name(), occupancy(), initiating_occupancy()); 1383 } 1384 return true; 1385 } 1386 if (UseCMSInitiatingOccupancyOnly) { 1387 return false; 1388 } 1389 if (expansion_cause() == CMSExpansionCause::_satisfy_allocation) { 1390 if (PrintGCDetails && Verbose) { 1391 gclog_or_tty->print(" %s: collect because expanded for allocation ", 1392 short_name()); 1393 } 1394 return true; 1395 } 1396 if (_cmsSpace->should_concurrent_collect()) { 1397 if (PrintGCDetails && Verbose) { 1398 gclog_or_tty->print(" %s: collect because cmsSpace says so ", 1399 short_name()); 1400 } 1401 return true; 1402 } 1403 return false; 1404 } 1405 1406 void ConcurrentMarkSweepGeneration::collect(bool full, 1407 bool clear_all_soft_refs, 1408 size_t size, 1409 bool tlab) 1410 { 1411 collector()->collect(full, clear_all_soft_refs, size, tlab); 1412 } 1413 1414 void CMSCollector::collect(bool full, 1415 bool clear_all_soft_refs, 1416 size_t size, 1417 bool tlab) 1418 { 1419 // The following "if" branch is present for defensive reasons. 1420 // In the current uses of this interface, it can be replaced with: 1421 // assert(!GC_locker.is_active(), "Can't be called otherwise"); 1422 // But I am not placing that assert here to allow future 1423 // generality in invoking this interface. 1424 if (GC_locker::is_active()) { 1425 // A consistency test for GC_locker 1426 assert(GC_locker::needs_gc(), "Should have been set already"); 1427 // Skip this foreground collection, instead 1428 // expanding the heap if necessary. 1429 // Need the free list locks for the call to free() in compute_new_size() 1430 compute_new_size(); 1431 return; 1432 } 1433 acquire_control_and_collect(full, clear_all_soft_refs); 1434 } 1435 1436 void CMSCollector::request_full_gc(unsigned int full_gc_count, GCCause::Cause cause) { 1437 GenCollectedHeap* gch = GenCollectedHeap::heap(); 1438 unsigned int gc_count = gch->total_full_collections(); 1439 if (gc_count == full_gc_count) { 1440 MutexLockerEx y(CGC_lock, Mutex::_no_safepoint_check_flag); 1441 _full_gc_requested = true; 1442 _full_gc_cause = cause; 1443 CGC_lock->notify(); // nudge CMS thread 1444 } else { 1445 assert(gc_count > full_gc_count, "Error: causal loop"); 1446 } 1447 } 1448 1449 bool CMSCollector::is_external_interruption() { 1450 GCCause::Cause cause = GenCollectedHeap::heap()->gc_cause(); 1451 return GCCause::is_user_requested_gc(cause) || 1452 GCCause::is_serviceability_requested_gc(cause); 1453 } 1454 1455 void CMSCollector::report_concurrent_mode_interruption() { 1456 if (is_external_interruption()) { 1457 if (PrintGCDetails) { 1458 gclog_or_tty->print(" (concurrent mode interrupted)"); 1459 } 1460 } else { 1461 if (PrintGCDetails) { 1462 gclog_or_tty->print(" (concurrent mode failure)"); 1463 } 1464 _gc_tracer_cm->report_concurrent_mode_failure(); 1465 } 1466 } 1467 1468 1469 // The foreground and background collectors need to coordinate in order 1470 // to make sure that they do not mutually interfere with CMS collections. 1471 // When a background collection is active, 1472 // the foreground collector may need to take over (preempt) and 1473 // synchronously complete an ongoing collection. Depending on the 1474 // frequency of the background collections and the heap usage 1475 // of the application, this preemption can be seldom or frequent. 1476 // There are only certain 1477 // points in the background collection that the "collection-baton" 1478 // can be passed to the foreground collector. 1479 // 1480 // The foreground collector will wait for the baton before 1481 // starting any part of the collection. The foreground collector 1482 // will only wait at one location. 1483 // 1484 // The background collector will yield the baton before starting a new 1485 // phase of the collection (e.g., before initial marking, marking from roots, 1486 // precleaning, final re-mark, sweep etc.) This is normally done at the head 1487 // of the loop which switches the phases. The background collector does some 1488 // of the phases (initial mark, final re-mark) with the world stopped. 1489 // Because of locking involved in stopping the world, 1490 // the foreground collector should not block waiting for the background 1491 // collector when it is doing a stop-the-world phase. The background 1492 // collector will yield the baton at an additional point just before 1493 // it enters a stop-the-world phase. Once the world is stopped, the 1494 // background collector checks the phase of the collection. If the 1495 // phase has not changed, it proceeds with the collection. If the 1496 // phase has changed, it skips that phase of the collection. See 1497 // the comments on the use of the Heap_lock in collect_in_background(). 1498 // 1499 // Variable used in baton passing. 1500 // _foregroundGCIsActive - Set to true by the foreground collector when 1501 // it wants the baton. The foreground clears it when it has finished 1502 // the collection. 1503 // _foregroundGCShouldWait - Set to true by the background collector 1504 // when it is running. The foreground collector waits while 1505 // _foregroundGCShouldWait is true. 1506 // CGC_lock - monitor used to protect access to the above variables 1507 // and to notify the foreground and background collectors. 1508 // _collectorState - current state of the CMS collection. 1509 // 1510 // The foreground collector 1511 // acquires the CGC_lock 1512 // sets _foregroundGCIsActive 1513 // waits on the CGC_lock for _foregroundGCShouldWait to be false 1514 // various locks acquired in preparation for the collection 1515 // are released so as not to block the background collector 1516 // that is in the midst of a collection 1517 // proceeds with the collection 1518 // clears _foregroundGCIsActive 1519 // returns 1520 // 1521 // The background collector in a loop iterating on the phases of the 1522 // collection 1523 // acquires the CGC_lock 1524 // sets _foregroundGCShouldWait 1525 // if _foregroundGCIsActive is set 1526 // clears _foregroundGCShouldWait, notifies _CGC_lock 1527 // waits on _CGC_lock for _foregroundGCIsActive to become false 1528 // and exits the loop. 1529 // otherwise 1530 // proceed with that phase of the collection 1531 // if the phase is a stop-the-world phase, 1532 // yield the baton once more just before enqueueing 1533 // the stop-world CMS operation (executed by the VM thread). 1534 // returns after all phases of the collection are done 1535 // 1536 1537 void CMSCollector::acquire_control_and_collect(bool full, 1538 bool clear_all_soft_refs) { 1539 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); 1540 assert(!Thread::current()->is_ConcurrentGC_thread(), 1541 "shouldn't try to acquire control from self!"); 1542 1543 // Start the protocol for acquiring control of the 1544 // collection from the background collector (aka CMS thread). 1545 assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(), 1546 "VM thread should have CMS token"); 1547 // Remember the possibly interrupted state of an ongoing 1548 // concurrent collection 1549 CollectorState first_state = _collectorState; 1550 1551 // Signal to a possibly ongoing concurrent collection that 1552 // we want to do a foreground collection. 1553 _foregroundGCIsActive = true; 1554 1555 // release locks and wait for a notify from the background collector 1556 // releasing the locks in only necessary for phases which 1557 // do yields to improve the granularity of the collection. 1558 assert_lock_strong(bitMapLock()); 1559 // We need to lock the Free list lock for the space that we are 1560 // currently collecting. 1561 assert(haveFreelistLocks(), "Must be holding free list locks"); 1562 bitMapLock()->unlock(); 1563 releaseFreelistLocks(); 1564 { 1565 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 1566 if (_foregroundGCShouldWait) { 1567 // We are going to be waiting for action for the CMS thread; 1568 // it had better not be gone (for instance at shutdown)! 1569 assert(ConcurrentMarkSweepThread::cmst() != NULL, 1570 "CMS thread must be running"); 1571 // Wait here until the background collector gives us the go-ahead 1572 ConcurrentMarkSweepThread::clear_CMS_flag( 1573 ConcurrentMarkSweepThread::CMS_vm_has_token); // release token 1574 // Get a possibly blocked CMS thread going: 1575 // Note that we set _foregroundGCIsActive true above, 1576 // without protection of the CGC_lock. 1577 CGC_lock->notify(); 1578 assert(!ConcurrentMarkSweepThread::vm_thread_wants_cms_token(), 1579 "Possible deadlock"); 1580 while (_foregroundGCShouldWait) { 1581 // wait for notification 1582 CGC_lock->wait(Mutex::_no_safepoint_check_flag); 1583 // Possibility of delay/starvation here, since CMS token does 1584 // not know to give priority to VM thread? Actually, i think 1585 // there wouldn't be any delay/starvation, but the proof of 1586 // that "fact" (?) appears non-trivial. XXX 20011219YSR 1587 } 1588 ConcurrentMarkSweepThread::set_CMS_flag( 1589 ConcurrentMarkSweepThread::CMS_vm_has_token); 1590 } 1591 } 1592 // The CMS_token is already held. Get back the other locks. 1593 assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(), 1594 "VM thread should have CMS token"); 1595 getFreelistLocks(); 1596 bitMapLock()->lock_without_safepoint_check(); 1597 if (TraceCMSState) { 1598 gclog_or_tty->print_cr("CMS foreground collector has asked for control " 1599 INTPTR_FORMAT " with first state %d", Thread::current(), first_state); 1600 gclog_or_tty->print_cr(" gets control with state %d", _collectorState); 1601 } 1602 1603 // Inform cms gen if this was due to partial collection failing. 1604 // The CMS gen may use this fact to determine its expansion policy. 1605 GenCollectedHeap* gch = GenCollectedHeap::heap(); 1606 if (gch->incremental_collection_will_fail(false /* don't consult_young */)) { 1607 assert(!_cmsGen->incremental_collection_failed(), 1608 "Should have been noticed, reacted to and cleared"); 1609 _cmsGen->set_incremental_collection_failed(); 1610 } 1611 1612 if (first_state > Idling) { 1613 report_concurrent_mode_interruption(); 1614 } 1615 1616 set_did_compact(true); 1617 1618 // If the collection is being acquired from the background 1619 // collector, there may be references on the discovered 1620 // references lists that have NULL referents (being those 1621 // that were concurrently cleared by a mutator) or 1622 // that are no longer active (having been enqueued concurrently 1623 // by the mutator). 1624 // Scrub the list of those references because Mark-Sweep-Compact 1625 // code assumes referents are not NULL and that all discovered 1626 // Reference objects are active. 1627 ref_processor()->clean_up_discovered_references(); 1628 1629 if (first_state > Idling) { 1630 save_heap_summary(); 1631 } 1632 1633 do_compaction_work(clear_all_soft_refs); 1634 1635 // Has the GC time limit been exceeded? 1636 DefNewGeneration* young_gen = _young_gen->as_DefNewGeneration(); 1637 size_t max_eden_size = young_gen->max_capacity() - 1638 young_gen->to()->capacity() - 1639 young_gen->from()->capacity(); 1640 GCCause::Cause gc_cause = gch->gc_cause(); 1641 size_policy()->check_gc_overhead_limit(_young_gen->used(), 1642 young_gen->eden()->used(), 1643 _cmsGen->max_capacity(), 1644 max_eden_size, 1645 full, 1646 gc_cause, 1647 gch->collector_policy()); 1648 1649 // Reset the expansion cause, now that we just completed 1650 // a collection cycle. 1651 clear_expansion_cause(); 1652 _foregroundGCIsActive = false; 1653 return; 1654 } 1655 1656 // Resize the tenured generation 1657 // after obtaining the free list locks for the 1658 // two generations. 1659 void CMSCollector::compute_new_size() { 1660 assert_locked_or_safepoint(Heap_lock); 1661 FreelistLocker z(this); 1662 MetaspaceGC::compute_new_size(); 1663 _cmsGen->compute_new_size_free_list(); 1664 } 1665 1666 // A work method used by the foreground collector to do 1667 // a mark-sweep-compact. 1668 void CMSCollector::do_compaction_work(bool clear_all_soft_refs) { 1669 GenCollectedHeap* gch = GenCollectedHeap::heap(); 1670 1671 STWGCTimer* gc_timer = GenMarkSweep::gc_timer(); 1672 gc_timer->register_gc_start(); 1673 1674 SerialOldTracer* gc_tracer = GenMarkSweep::gc_tracer(); 1675 gc_tracer->report_gc_start(gch->gc_cause(), gc_timer->gc_start()); 1676 1677 GCTraceTime t("CMS:MSC ", PrintGCDetails && Verbose, true, NULL, gc_tracer->gc_id()); 1678 1679 // Temporarily widen the span of the weak reference processing to 1680 // the entire heap. 1681 MemRegion new_span(GenCollectedHeap::heap()->reserved_region()); 1682 ReferenceProcessorSpanMutator rp_mut_span(ref_processor(), new_span); 1683 // Temporarily, clear the "is_alive_non_header" field of the 1684 // reference processor. 1685 ReferenceProcessorIsAliveMutator rp_mut_closure(ref_processor(), NULL); 1686 // Temporarily make reference _processing_ single threaded (non-MT). 1687 ReferenceProcessorMTProcMutator rp_mut_mt_processing(ref_processor(), false); 1688 // Temporarily make refs discovery atomic 1689 ReferenceProcessorAtomicMutator rp_mut_atomic(ref_processor(), true); 1690 // Temporarily make reference _discovery_ single threaded (non-MT) 1691 ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(ref_processor(), false); 1692 1693 ref_processor()->set_enqueuing_is_done(false); 1694 ref_processor()->enable_discovery(false /*verify_disabled*/, false /*check_no_refs*/); 1695 ref_processor()->setup_policy(clear_all_soft_refs); 1696 // If an asynchronous collection finishes, the _modUnionTable is 1697 // all clear. If we are assuming the collection from an asynchronous 1698 // collection, clear the _modUnionTable. 1699 assert(_collectorState != Idling || _modUnionTable.isAllClear(), 1700 "_modUnionTable should be clear if the baton was not passed"); 1701 _modUnionTable.clear_all(); 1702 assert(_collectorState != Idling || _ct->klass_rem_set()->mod_union_is_clear(), 1703 "mod union for klasses should be clear if the baton was passed"); 1704 _ct->klass_rem_set()->clear_mod_union(); 1705 1706 // We must adjust the allocation statistics being maintained 1707 // in the free list space. We do so by reading and clearing 1708 // the sweep timer and updating the block flux rate estimates below. 1709 assert(!_intra_sweep_timer.is_active(), "_intra_sweep_timer should be inactive"); 1710 if (_inter_sweep_timer.is_active()) { 1711 _inter_sweep_timer.stop(); 1712 // Note that we do not use this sample to update the _inter_sweep_estimate. 1713 _cmsGen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()), 1714 _inter_sweep_estimate.padded_average(), 1715 _intra_sweep_estimate.padded_average()); 1716 } 1717 1718 GenMarkSweep::invoke_at_safepoint(_cmsGen->level(), 1719 ref_processor(), clear_all_soft_refs); 1720 #ifdef ASSERT 1721 CompactibleFreeListSpace* cms_space = _cmsGen->cmsSpace(); 1722 size_t free_size = cms_space->free(); 1723 assert(free_size == 1724 pointer_delta(cms_space->end(), cms_space->compaction_top()) 1725 * HeapWordSize, 1726 "All the free space should be compacted into one chunk at top"); 1727 assert(cms_space->dictionary()->total_chunk_size( 1728 debug_only(cms_space->freelistLock())) == 0 || 1729 cms_space->totalSizeInIndexedFreeLists() == 0, 1730 "All the free space should be in a single chunk"); 1731 size_t num = cms_space->totalCount(); 1732 assert((free_size == 0 && num == 0) || 1733 (free_size > 0 && (num == 1 || num == 2)), 1734 "There should be at most 2 free chunks after compaction"); 1735 #endif // ASSERT 1736 _collectorState = Resetting; 1737 assert(_restart_addr == NULL, 1738 "Should have been NULL'd before baton was passed"); 1739 reset(false /* == !concurrent */); 1740 _cmsGen->reset_after_compaction(); 1741 _concurrent_cycles_since_last_unload = 0; 1742 1743 // Clear any data recorded in the PLAB chunk arrays. 1744 if (_survivor_plab_array != NULL) { 1745 reset_survivor_plab_arrays(); 1746 } 1747 1748 // Adjust the per-size allocation stats for the next epoch. 1749 _cmsGen->cmsSpace()->endSweepFLCensus(sweep_count() /* fake */); 1750 // Restart the "inter sweep timer" for the next epoch. 1751 _inter_sweep_timer.reset(); 1752 _inter_sweep_timer.start(); 1753 1754 gc_timer->register_gc_end(); 1755 1756 gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions()); 1757 1758 // For a mark-sweep-compact, compute_new_size() will be called 1759 // in the heap's do_collection() method. 1760 } 1761 1762 void CMSCollector::print_eden_and_survivor_chunk_arrays() { 1763 DefNewGeneration* dng = _young_gen->as_DefNewGeneration(); 1764 ContiguousSpace* eden_space = dng->eden(); 1765 ContiguousSpace* from_space = dng->from(); 1766 ContiguousSpace* to_space = dng->to(); 1767 // Eden 1768 if (_eden_chunk_array != NULL) { 1769 gclog_or_tty->print_cr("eden " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")", 1770 eden_space->bottom(), eden_space->top(), 1771 eden_space->end(), eden_space->capacity()); 1772 gclog_or_tty->print_cr("_eden_chunk_index=" SIZE_FORMAT ", " 1773 "_eden_chunk_capacity=" SIZE_FORMAT, 1774 _eden_chunk_index, _eden_chunk_capacity); 1775 for (size_t i = 0; i < _eden_chunk_index; i++) { 1776 gclog_or_tty->print_cr("_eden_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT, 1777 i, _eden_chunk_array[i]); 1778 } 1779 } 1780 // Survivor 1781 if (_survivor_chunk_array != NULL) { 1782 gclog_or_tty->print_cr("survivor " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")", 1783 from_space->bottom(), from_space->top(), 1784 from_space->end(), from_space->capacity()); 1785 gclog_or_tty->print_cr("_survivor_chunk_index=" SIZE_FORMAT ", " 1786 "_survivor_chunk_capacity=" SIZE_FORMAT, 1787 _survivor_chunk_index, _survivor_chunk_capacity); 1788 for (size_t i = 0; i < _survivor_chunk_index; i++) { 1789 gclog_or_tty->print_cr("_survivor_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT, 1790 i, _survivor_chunk_array[i]); 1791 } 1792 } 1793 } 1794 1795 void CMSCollector::getFreelistLocks() const { 1796 // Get locks for all free lists in all generations that this 1797 // collector is responsible for 1798 _cmsGen->freelistLock()->lock_without_safepoint_check(); 1799 } 1800 1801 void CMSCollector::releaseFreelistLocks() const { 1802 // Release locks for all free lists in all generations that this 1803 // collector is responsible for 1804 _cmsGen->freelistLock()->unlock(); 1805 } 1806 1807 bool CMSCollector::haveFreelistLocks() const { 1808 // Check locks for all free lists in all generations that this 1809 // collector is responsible for 1810 assert_lock_strong(_cmsGen->freelistLock()); 1811 PRODUCT_ONLY(ShouldNotReachHere()); 1812 return true; 1813 } 1814 1815 // A utility class that is used by the CMS collector to 1816 // temporarily "release" the foreground collector from its 1817 // usual obligation to wait for the background collector to 1818 // complete an ongoing phase before proceeding. 1819 class ReleaseForegroundGC: public StackObj { 1820 private: 1821 CMSCollector* _c; 1822 public: 1823 ReleaseForegroundGC(CMSCollector* c) : _c(c) { 1824 assert(_c->_foregroundGCShouldWait, "Else should not need to call"); 1825 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 1826 // allow a potentially blocked foreground collector to proceed 1827 _c->_foregroundGCShouldWait = false; 1828 if (_c->_foregroundGCIsActive) { 1829 CGC_lock->notify(); 1830 } 1831 assert(!ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 1832 "Possible deadlock"); 1833 } 1834 1835 ~ReleaseForegroundGC() { 1836 assert(!_c->_foregroundGCShouldWait, "Usage protocol violation?"); 1837 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 1838 _c->_foregroundGCShouldWait = true; 1839 } 1840 }; 1841 1842 void CMSCollector::collect_in_background(GCCause::Cause cause) { 1843 assert(Thread::current()->is_ConcurrentGC_thread(), 1844 "A CMS asynchronous collection is only allowed on a CMS thread."); 1845 1846 GenCollectedHeap* gch = GenCollectedHeap::heap(); 1847 { 1848 bool safepoint_check = Mutex::_no_safepoint_check_flag; 1849 MutexLockerEx hl(Heap_lock, safepoint_check); 1850 FreelistLocker fll(this); 1851 MutexLockerEx x(CGC_lock, safepoint_check); 1852 if (_foregroundGCIsActive || !UseAsyncConcMarkSweepGC) { 1853 // The foreground collector is active or we're 1854 // not using asynchronous collections. Skip this 1855 // background collection. 1856 assert(!_foregroundGCShouldWait, "Should be clear"); 1857 return; 1858 } else { 1859 assert(_collectorState == Idling, "Should be idling before start."); 1860 _collectorState = InitialMarking; 1861 register_gc_start(cause); 1862 // Reset the expansion cause, now that we are about to begin 1863 // a new cycle. 1864 clear_expansion_cause(); 1865 1866 // Clear the MetaspaceGC flag since a concurrent collection 1867 // is starting but also clear it after the collection. 1868 MetaspaceGC::set_should_concurrent_collect(false); 1869 } 1870 // Decide if we want to enable class unloading as part of the 1871 // ensuing concurrent GC cycle. 1872 update_should_unload_classes(); 1873 _full_gc_requested = false; // acks all outstanding full gc requests 1874 _full_gc_cause = GCCause::_no_gc; 1875 // Signal that we are about to start a collection 1876 gch->increment_total_full_collections(); // ... starting a collection cycle 1877 _collection_count_start = gch->total_full_collections(); 1878 } 1879 1880 // Used for PrintGC 1881 size_t prev_used; 1882 if (PrintGC && Verbose) { 1883 prev_used = _cmsGen->used(); 1884 } 1885 1886 // The change of the collection state is normally done at this level; 1887 // the exceptions are phases that are executed while the world is 1888 // stopped. For those phases the change of state is done while the 1889 // world is stopped. For baton passing purposes this allows the 1890 // background collector to finish the phase and change state atomically. 1891 // The foreground collector cannot wait on a phase that is done 1892 // while the world is stopped because the foreground collector already 1893 // has the world stopped and would deadlock. 1894 while (_collectorState != Idling) { 1895 if (TraceCMSState) { 1896 gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " in CMS state %d", 1897 Thread::current(), _collectorState); 1898 } 1899 // The foreground collector 1900 // holds the Heap_lock throughout its collection. 1901 // holds the CMS token (but not the lock) 1902 // except while it is waiting for the background collector to yield. 1903 // 1904 // The foreground collector should be blocked (not for long) 1905 // if the background collector is about to start a phase 1906 // executed with world stopped. If the background 1907 // collector has already started such a phase, the 1908 // foreground collector is blocked waiting for the 1909 // Heap_lock. The stop-world phases (InitialMarking and FinalMarking) 1910 // are executed in the VM thread. 1911 // 1912 // The locking order is 1913 // PendingListLock (PLL) -- if applicable (FinalMarking) 1914 // Heap_lock (both this & PLL locked in VM_CMS_Operation::prologue()) 1915 // CMS token (claimed in 1916 // stop_world_and_do() --> 1917 // safepoint_synchronize() --> 1918 // CMSThread::synchronize()) 1919 1920 { 1921 // Check if the FG collector wants us to yield. 1922 CMSTokenSync x(true); // is cms thread 1923 if (waitForForegroundGC()) { 1924 // We yielded to a foreground GC, nothing more to be 1925 // done this round. 1926 assert(_foregroundGCShouldWait == false, "We set it to false in " 1927 "waitForForegroundGC()"); 1928 if (TraceCMSState) { 1929 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT 1930 " exiting collection CMS state %d", 1931 Thread::current(), _collectorState); 1932 } 1933 return; 1934 } else { 1935 // The background collector can run but check to see if the 1936 // foreground collector has done a collection while the 1937 // background collector was waiting to get the CGC_lock 1938 // above. If yes, break so that _foregroundGCShouldWait 1939 // is cleared before returning. 1940 if (_collectorState == Idling) { 1941 break; 1942 } 1943 } 1944 } 1945 1946 assert(_foregroundGCShouldWait, "Foreground collector, if active, " 1947 "should be waiting"); 1948 1949 switch (_collectorState) { 1950 case InitialMarking: 1951 { 1952 ReleaseForegroundGC x(this); 1953 stats().record_cms_begin(); 1954 VM_CMS_Initial_Mark initial_mark_op(this); 1955 VMThread::execute(&initial_mark_op); 1956 } 1957 // The collector state may be any legal state at this point 1958 // since the background collector may have yielded to the 1959 // foreground collector. 1960 break; 1961 case Marking: 1962 // initial marking in checkpointRootsInitialWork has been completed 1963 if (markFromRoots()) { // we were successful 1964 assert(_collectorState == Precleaning, "Collector state should " 1965 "have changed"); 1966 } else { 1967 assert(_foregroundGCIsActive, "Internal state inconsistency"); 1968 } 1969 break; 1970 case Precleaning: 1971 // marking from roots in markFromRoots has been completed 1972 preclean(); 1973 assert(_collectorState == AbortablePreclean || 1974 _collectorState == FinalMarking, 1975 "Collector state should have changed"); 1976 break; 1977 case AbortablePreclean: 1978 abortable_preclean(); 1979 assert(_collectorState == FinalMarking, "Collector state should " 1980 "have changed"); 1981 break; 1982 case FinalMarking: 1983 { 1984 ReleaseForegroundGC x(this); 1985 1986 VM_CMS_Final_Remark final_remark_op(this); 1987 VMThread::execute(&final_remark_op); 1988 } 1989 assert(_foregroundGCShouldWait, "block post-condition"); 1990 break; 1991 case Sweeping: 1992 // final marking in checkpointRootsFinal has been completed 1993 sweep(); 1994 assert(_collectorState == Resizing, "Collector state change " 1995 "to Resizing must be done under the free_list_lock"); 1996 1997 case Resizing: { 1998 // Sweeping has been completed... 1999 // At this point the background collection has completed. 2000 // Don't move the call to compute_new_size() down 2001 // into code that might be executed if the background 2002 // collection was preempted. 2003 { 2004 ReleaseForegroundGC x(this); // unblock FG collection 2005 MutexLockerEx y(Heap_lock, Mutex::_no_safepoint_check_flag); 2006 CMSTokenSync z(true); // not strictly needed. 2007 if (_collectorState == Resizing) { 2008 compute_new_size(); 2009 save_heap_summary(); 2010 _collectorState = Resetting; 2011 } else { 2012 assert(_collectorState == Idling, "The state should only change" 2013 " because the foreground collector has finished the collection"); 2014 } 2015 } 2016 break; 2017 } 2018 case Resetting: 2019 // CMS heap resizing has been completed 2020 reset(true); 2021 assert(_collectorState == Idling, "Collector state should " 2022 "have changed"); 2023 2024 MetaspaceGC::set_should_concurrent_collect(false); 2025 2026 stats().record_cms_end(); 2027 // Don't move the concurrent_phases_end() and compute_new_size() 2028 // calls to here because a preempted background collection 2029 // has it's state set to "Resetting". 2030 break; 2031 case Idling: 2032 default: 2033 ShouldNotReachHere(); 2034 break; 2035 } 2036 if (TraceCMSState) { 2037 gclog_or_tty->print_cr(" Thread " INTPTR_FORMAT " done - next CMS state %d", 2038 Thread::current(), _collectorState); 2039 } 2040 assert(_foregroundGCShouldWait, "block post-condition"); 2041 } 2042 2043 // Should this be in gc_epilogue? 2044 collector_policy()->counters()->update_counters(); 2045 2046 { 2047 // Clear _foregroundGCShouldWait and, in the event that the 2048 // foreground collector is waiting, notify it, before 2049 // returning. 2050 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 2051 _foregroundGCShouldWait = false; 2052 if (_foregroundGCIsActive) { 2053 CGC_lock->notify(); 2054 } 2055 assert(!ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 2056 "Possible deadlock"); 2057 } 2058 if (TraceCMSState) { 2059 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT 2060 " exiting collection CMS state %d", 2061 Thread::current(), _collectorState); 2062 } 2063 if (PrintGC && Verbose) { 2064 _cmsGen->print_heap_change(prev_used); 2065 } 2066 } 2067 2068 void CMSCollector::register_gc_start(GCCause::Cause cause) { 2069 _cms_start_registered = true; 2070 _gc_timer_cm->register_gc_start(); 2071 _gc_tracer_cm->report_gc_start(cause, _gc_timer_cm->gc_start()); 2072 } 2073 2074 void CMSCollector::register_gc_end() { 2075 if (_cms_start_registered) { 2076 report_heap_summary(GCWhen::AfterGC); 2077 2078 _gc_timer_cm->register_gc_end(); 2079 _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions()); 2080 _cms_start_registered = false; 2081 } 2082 } 2083 2084 void CMSCollector::save_heap_summary() { 2085 GenCollectedHeap* gch = GenCollectedHeap::heap(); 2086 _last_heap_summary = gch->create_heap_summary(); 2087 _last_metaspace_summary = gch->create_metaspace_summary(); 2088 } 2089 2090 void CMSCollector::report_heap_summary(GCWhen::Type when) { 2091 _gc_tracer_cm->report_gc_heap_summary(when, _last_heap_summary); 2092 _gc_tracer_cm->report_metaspace_summary(when, _last_metaspace_summary); 2093 } 2094 2095 bool CMSCollector::waitForForegroundGC() { 2096 bool res = false; 2097 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 2098 "CMS thread should have CMS token"); 2099 // Block the foreground collector until the 2100 // background collectors decides whether to 2101 // yield. 2102 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 2103 _foregroundGCShouldWait = true; 2104 if (_foregroundGCIsActive) { 2105 // The background collector yields to the 2106 // foreground collector and returns a value 2107 // indicating that it has yielded. The foreground 2108 // collector can proceed. 2109 res = true; 2110 _foregroundGCShouldWait = false; 2111 ConcurrentMarkSweepThread::clear_CMS_flag( 2112 ConcurrentMarkSweepThread::CMS_cms_has_token); 2113 ConcurrentMarkSweepThread::set_CMS_flag( 2114 ConcurrentMarkSweepThread::CMS_cms_wants_token); 2115 // Get a possibly blocked foreground thread going 2116 CGC_lock->notify(); 2117 if (TraceCMSState) { 2118 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " waiting at CMS state %d", 2119 Thread::current(), _collectorState); 2120 } 2121 while (_foregroundGCIsActive) { 2122 CGC_lock->wait(Mutex::_no_safepoint_check_flag); 2123 } 2124 ConcurrentMarkSweepThread::set_CMS_flag( 2125 ConcurrentMarkSweepThread::CMS_cms_has_token); 2126 ConcurrentMarkSweepThread::clear_CMS_flag( 2127 ConcurrentMarkSweepThread::CMS_cms_wants_token); 2128 } 2129 if (TraceCMSState) { 2130 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " continuing at CMS state %d", 2131 Thread::current(), _collectorState); 2132 } 2133 return res; 2134 } 2135 2136 // Because of the need to lock the free lists and other structures in 2137 // the collector, common to all the generations that the collector is 2138 // collecting, we need the gc_prologues of individual CMS generations 2139 // delegate to their collector. It may have been simpler had the 2140 // current infrastructure allowed one to call a prologue on a 2141 // collector. In the absence of that we have the generation's 2142 // prologue delegate to the collector, which delegates back 2143 // some "local" work to a worker method in the individual generations 2144 // that it's responsible for collecting, while itself doing any 2145 // work common to all generations it's responsible for. A similar 2146 // comment applies to the gc_epilogue()'s. 2147 // The role of the variable _between_prologue_and_epilogue is to 2148 // enforce the invocation protocol. 2149 void CMSCollector::gc_prologue(bool full) { 2150 // Call gc_prologue_work() for the CMSGen 2151 // we are responsible for. 2152 2153 // The following locking discipline assumes that we are only called 2154 // when the world is stopped. 2155 assert(SafepointSynchronize::is_at_safepoint(), "world is stopped assumption"); 2156 2157 // The CMSCollector prologue must call the gc_prologues for the 2158 // "generations" that it's responsible 2159 // for. 2160 2161 assert( Thread::current()->is_VM_thread() 2162 || ( CMSScavengeBeforeRemark 2163 && Thread::current()->is_ConcurrentGC_thread()), 2164 "Incorrect thread type for prologue execution"); 2165 2166 if (_between_prologue_and_epilogue) { 2167 // We have already been invoked; this is a gc_prologue delegation 2168 // from yet another CMS generation that we are responsible for, just 2169 // ignore it since all relevant work has already been done. 2170 return; 2171 } 2172 2173 // set a bit saying prologue has been called; cleared in epilogue 2174 _between_prologue_and_epilogue = true; 2175 // Claim locks for common data structures, then call gc_prologue_work() 2176 // for each CMSGen. 2177 2178 getFreelistLocks(); // gets free list locks on constituent spaces 2179 bitMapLock()->lock_without_safepoint_check(); 2180 2181 // Should call gc_prologue_work() for all cms gens we are responsible for 2182 bool duringMarking = _collectorState >= Marking 2183 && _collectorState < Sweeping; 2184 2185 // The young collections clear the modified oops state, which tells if 2186 // there are any modified oops in the class. The remark phase also needs 2187 // that information. Tell the young collection to save the union of all 2188 // modified klasses. 2189 if (duringMarking) { 2190 _ct->klass_rem_set()->set_accumulate_modified_oops(true); 2191 } 2192 2193 bool registerClosure = duringMarking; 2194 2195 ModUnionClosure* muc = CollectedHeap::use_parallel_gc_threads() ? 2196 &_modUnionClosurePar 2197 : &_modUnionClosure; 2198 _cmsGen->gc_prologue_work(full, registerClosure, muc); 2199 2200 if (!full) { 2201 stats().record_gc0_begin(); 2202 } 2203 } 2204 2205 void ConcurrentMarkSweepGeneration::gc_prologue(bool full) { 2206 2207 _capacity_at_prologue = capacity(); 2208 _used_at_prologue = used(); 2209 2210 // Delegate to CMScollector which knows how to coordinate between 2211 // this and any other CMS generations that it is responsible for 2212 // collecting. 2213 collector()->gc_prologue(full); 2214 } 2215 2216 // This is a "private" interface for use by this generation's CMSCollector. 2217 // Not to be called directly by any other entity (for instance, 2218 // GenCollectedHeap, which calls the "public" gc_prologue method above). 2219 void ConcurrentMarkSweepGeneration::gc_prologue_work(bool full, 2220 bool registerClosure, ModUnionClosure* modUnionClosure) { 2221 assert(!incremental_collection_failed(), "Shouldn't be set yet"); 2222 assert(cmsSpace()->preconsumptionDirtyCardClosure() == NULL, 2223 "Should be NULL"); 2224 if (registerClosure) { 2225 cmsSpace()->setPreconsumptionDirtyCardClosure(modUnionClosure); 2226 } 2227 cmsSpace()->gc_prologue(); 2228 // Clear stat counters 2229 NOT_PRODUCT( 2230 assert(_numObjectsPromoted == 0, "check"); 2231 assert(_numWordsPromoted == 0, "check"); 2232 if (Verbose && PrintGC) { 2233 gclog_or_tty->print("Allocated "SIZE_FORMAT" objects, " 2234 SIZE_FORMAT" bytes concurrently", 2235 _numObjectsAllocated, _numWordsAllocated*sizeof(HeapWord)); 2236 } 2237 _numObjectsAllocated = 0; 2238 _numWordsAllocated = 0; 2239 ) 2240 } 2241 2242 void CMSCollector::gc_epilogue(bool full) { 2243 // The following locking discipline assumes that we are only called 2244 // when the world is stopped. 2245 assert(SafepointSynchronize::is_at_safepoint(), 2246 "world is stopped assumption"); 2247 2248 // Currently the CMS epilogue (see CompactibleFreeListSpace) merely checks 2249 // if linear allocation blocks need to be appropriately marked to allow the 2250 // the blocks to be parsable. We also check here whether we need to nudge the 2251 // CMS collector thread to start a new cycle (if it's not already active). 2252 assert( Thread::current()->is_VM_thread() 2253 || ( CMSScavengeBeforeRemark 2254 && Thread::current()->is_ConcurrentGC_thread()), 2255 "Incorrect thread type for epilogue execution"); 2256 2257 if (!_between_prologue_and_epilogue) { 2258 // We have already been invoked; this is a gc_epilogue delegation 2259 // from yet another CMS generation that we are responsible for, just 2260 // ignore it since all relevant work has already been done. 2261 return; 2262 } 2263 assert(haveFreelistLocks(), "must have freelist locks"); 2264 assert_lock_strong(bitMapLock()); 2265 2266 _ct->klass_rem_set()->set_accumulate_modified_oops(false); 2267 2268 _cmsGen->gc_epilogue_work(full); 2269 2270 if (_collectorState == AbortablePreclean || _collectorState == Precleaning) { 2271 // in case sampling was not already enabled, enable it 2272 _start_sampling = true; 2273 } 2274 // reset _eden_chunk_array so sampling starts afresh 2275 _eden_chunk_index = 0; 2276 2277 size_t cms_used = _cmsGen->cmsSpace()->used(); 2278 2279 // update performance counters - this uses a special version of 2280 // update_counters() that allows the utilization to be passed as a 2281 // parameter, avoiding multiple calls to used(). 2282 // 2283 _cmsGen->update_counters(cms_used); 2284 2285 bitMapLock()->unlock(); 2286 releaseFreelistLocks(); 2287 2288 if (!CleanChunkPoolAsync) { 2289 Chunk::clean_chunk_pool(); 2290 } 2291 2292 set_did_compact(false); 2293 _between_prologue_and_epilogue = false; // ready for next cycle 2294 } 2295 2296 void ConcurrentMarkSweepGeneration::gc_epilogue(bool full) { 2297 collector()->gc_epilogue(full); 2298 2299 // Also reset promotion tracking in par gc thread states. 2300 for (uint i = 0; i < ParallelGCThreads; i++) { 2301 _par_gc_thread_states[i]->promo.stopTrackingPromotions(i); 2302 } 2303 } 2304 2305 void ConcurrentMarkSweepGeneration::gc_epilogue_work(bool full) { 2306 assert(!incremental_collection_failed(), "Should have been cleared"); 2307 cmsSpace()->setPreconsumptionDirtyCardClosure(NULL); 2308 cmsSpace()->gc_epilogue(); 2309 // Print stat counters 2310 NOT_PRODUCT( 2311 assert(_numObjectsAllocated == 0, "check"); 2312 assert(_numWordsAllocated == 0, "check"); 2313 if (Verbose && PrintGC) { 2314 gclog_or_tty->print("Promoted "SIZE_FORMAT" objects, " 2315 SIZE_FORMAT" bytes", 2316 _numObjectsPromoted, _numWordsPromoted*sizeof(HeapWord)); 2317 } 2318 _numObjectsPromoted = 0; 2319 _numWordsPromoted = 0; 2320 ) 2321 2322 if (PrintGC && Verbose) { 2323 // Call down the chain in contiguous_available needs the freelistLock 2324 // so print this out before releasing the freeListLock. 2325 gclog_or_tty->print(" Contiguous available "SIZE_FORMAT" bytes ", 2326 contiguous_available()); 2327 } 2328 } 2329 2330 #ifndef PRODUCT 2331 bool CMSCollector::have_cms_token() { 2332 Thread* thr = Thread::current(); 2333 if (thr->is_VM_thread()) { 2334 return ConcurrentMarkSweepThread::vm_thread_has_cms_token(); 2335 } else if (thr->is_ConcurrentGC_thread()) { 2336 return ConcurrentMarkSweepThread::cms_thread_has_cms_token(); 2337 } else if (thr->is_GC_task_thread()) { 2338 return ConcurrentMarkSweepThread::vm_thread_has_cms_token() && 2339 ParGCRareEvent_lock->owned_by_self(); 2340 } 2341 return false; 2342 } 2343 #endif 2344 2345 // Check reachability of the given heap address in CMS generation, 2346 // treating all other generations as roots. 2347 bool CMSCollector::is_cms_reachable(HeapWord* addr) { 2348 // We could "guarantee" below, rather than assert, but I'll 2349 // leave these as "asserts" so that an adventurous debugger 2350 // could try this in the product build provided some subset of 2351 // the conditions were met, provided they were interested in the 2352 // results and knew that the computation below wouldn't interfere 2353 // with other concurrent computations mutating the structures 2354 // being read or written. 2355 assert(SafepointSynchronize::is_at_safepoint(), 2356 "Else mutations in object graph will make answer suspect"); 2357 assert(have_cms_token(), "Should hold cms token"); 2358 assert(haveFreelistLocks(), "must hold free list locks"); 2359 assert_lock_strong(bitMapLock()); 2360 2361 // Clear the marking bit map array before starting, but, just 2362 // for kicks, first report if the given address is already marked 2363 gclog_or_tty->print_cr("Start: Address " PTR_FORMAT " is%s marked", addr, 2364 _markBitMap.isMarked(addr) ? "" : " not"); 2365 2366 if (verify_after_remark()) { 2367 MutexLockerEx x(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag); 2368 bool result = verification_mark_bm()->isMarked(addr); 2369 gclog_or_tty->print_cr("TransitiveMark: Address " PTR_FORMAT " %s marked", addr, 2370 result ? "IS" : "is NOT"); 2371 return result; 2372 } else { 2373 gclog_or_tty->print_cr("Could not compute result"); 2374 return false; 2375 } 2376 } 2377 2378 2379 void 2380 CMSCollector::print_on_error(outputStream* st) { 2381 CMSCollector* collector = ConcurrentMarkSweepGeneration::_collector; 2382 if (collector != NULL) { 2383 CMSBitMap* bitmap = &collector->_markBitMap; 2384 st->print_cr("Marking Bits: (CMSBitMap*) " PTR_FORMAT, bitmap); 2385 bitmap->print_on_error(st, " Bits: "); 2386 2387 st->cr(); 2388 2389 CMSBitMap* mut_bitmap = &collector->_modUnionTable; 2390 st->print_cr("Mod Union Table: (CMSBitMap*) " PTR_FORMAT, mut_bitmap); 2391 mut_bitmap->print_on_error(st, " Bits: "); 2392 } 2393 } 2394 2395 //////////////////////////////////////////////////////// 2396 // CMS Verification Support 2397 //////////////////////////////////////////////////////// 2398 // Following the remark phase, the following invariant 2399 // should hold -- each object in the CMS heap which is 2400 // marked in markBitMap() should be marked in the verification_mark_bm(). 2401 2402 class VerifyMarkedClosure: public BitMapClosure { 2403 CMSBitMap* _marks; 2404 bool _failed; 2405 2406 public: 2407 VerifyMarkedClosure(CMSBitMap* bm): _marks(bm), _failed(false) {} 2408 2409 bool do_bit(size_t offset) { 2410 HeapWord* addr = _marks->offsetToHeapWord(offset); 2411 if (!_marks->isMarked(addr)) { 2412 oop(addr)->print_on(gclog_or_tty); 2413 gclog_or_tty->print_cr(" ("INTPTR_FORMAT" should have been marked)", addr); 2414 _failed = true; 2415 } 2416 return true; 2417 } 2418 2419 bool failed() { return _failed; } 2420 }; 2421 2422 bool CMSCollector::verify_after_remark(bool silent) { 2423 if (!silent) gclog_or_tty->print(" [Verifying CMS Marking... "); 2424 MutexLockerEx ml(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag); 2425 static bool init = false; 2426 2427 assert(SafepointSynchronize::is_at_safepoint(), 2428 "Else mutations in object graph will make answer suspect"); 2429 assert(have_cms_token(), 2430 "Else there may be mutual interference in use of " 2431 " verification data structures"); 2432 assert(_collectorState > Marking && _collectorState <= Sweeping, 2433 "Else marking info checked here may be obsolete"); 2434 assert(haveFreelistLocks(), "must hold free list locks"); 2435 assert_lock_strong(bitMapLock()); 2436 2437 2438 // Allocate marking bit map if not already allocated 2439 if (!init) { // first time 2440 if (!verification_mark_bm()->allocate(_span)) { 2441 return false; 2442 } 2443 init = true; 2444 } 2445 2446 assert(verification_mark_stack()->isEmpty(), "Should be empty"); 2447 2448 // Turn off refs discovery -- so we will be tracing through refs. 2449 // This is as intended, because by this time 2450 // GC must already have cleared any refs that need to be cleared, 2451 // and traced those that need to be marked; moreover, 2452 // the marking done here is not going to interfere in any 2453 // way with the marking information used by GC. 2454 NoRefDiscovery no_discovery(ref_processor()); 2455 2456 COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;) 2457 2458 // Clear any marks from a previous round 2459 verification_mark_bm()->clear_all(); 2460 assert(verification_mark_stack()->isEmpty(), "markStack should be empty"); 2461 verify_work_stacks_empty(); 2462 2463 GenCollectedHeap* gch = GenCollectedHeap::heap(); 2464 gch->ensure_parsability(false); // fill TLABs, but no need to retire them 2465 // Update the saved marks which may affect the root scans. 2466 gch->save_marks(); 2467 2468 if (CMSRemarkVerifyVariant == 1) { 2469 // In this first variant of verification, we complete 2470 // all marking, then check if the new marks-vector is 2471 // a subset of the CMS marks-vector. 2472 verify_after_remark_work_1(); 2473 } else if (CMSRemarkVerifyVariant == 2) { 2474 // In this second variant of verification, we flag an error 2475 // (i.e. an object reachable in the new marks-vector not reachable 2476 // in the CMS marks-vector) immediately, also indicating the 2477 // identify of an object (A) that references the unmarked object (B) -- 2478 // presumably, a mutation to A failed to be picked up by preclean/remark? 2479 verify_after_remark_work_2(); 2480 } else { 2481 warning("Unrecognized value %d for CMSRemarkVerifyVariant", 2482 CMSRemarkVerifyVariant); 2483 } 2484 if (!silent) gclog_or_tty->print(" done] "); 2485 return true; 2486 } 2487 2488 void CMSCollector::verify_after_remark_work_1() { 2489 ResourceMark rm; 2490 HandleMark hm; 2491 GenCollectedHeap* gch = GenCollectedHeap::heap(); 2492 2493 // Get a clear set of claim bits for the roots processing to work with. 2494 ClassLoaderDataGraph::clear_claimed_marks(); 2495 2496 // Mark from roots one level into CMS 2497 MarkRefsIntoClosure notOlder(_span, verification_mark_bm()); 2498 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel. 2499 2500 gch->gen_process_roots(_cmsGen->level(), 2501 true, // younger gens are roots 2502 true, // activate StrongRootsScope 2503 SharedHeap::ScanningOption(roots_scanning_options()), 2504 should_unload_classes(), 2505 ¬Older, 2506 NULL, 2507 NULL); // SSS: Provide correct closure 2508 2509 // Now mark from the roots 2510 MarkFromRootsClosure markFromRootsClosure(this, _span, 2511 verification_mark_bm(), verification_mark_stack(), 2512 false /* don't yield */, true /* verifying */); 2513 assert(_restart_addr == NULL, "Expected pre-condition"); 2514 verification_mark_bm()->iterate(&markFromRootsClosure); 2515 while (_restart_addr != NULL) { 2516 // Deal with stack overflow: by restarting at the indicated 2517 // address. 2518 HeapWord* ra = _restart_addr; 2519 markFromRootsClosure.reset(ra); 2520 _restart_addr = NULL; 2521 verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end()); 2522 } 2523 assert(verification_mark_stack()->isEmpty(), "Should have been drained"); 2524 verify_work_stacks_empty(); 2525 2526 // Marking completed -- now verify that each bit marked in 2527 // verification_mark_bm() is also marked in markBitMap(); flag all 2528 // errors by printing corresponding objects. 2529 VerifyMarkedClosure vcl(markBitMap()); 2530 verification_mark_bm()->iterate(&vcl); 2531 if (vcl.failed()) { 2532 gclog_or_tty->print("Verification failed"); 2533 Universe::heap()->print_on(gclog_or_tty); 2534 fatal("CMS: failed marking verification after remark"); 2535 } 2536 } 2537 2538 class VerifyKlassOopsKlassClosure : public KlassClosure { 2539 class VerifyKlassOopsClosure : public OopClosure { 2540 CMSBitMap* _bitmap; 2541 public: 2542 VerifyKlassOopsClosure(CMSBitMap* bitmap) : _bitmap(bitmap) { } 2543 void do_oop(oop* p) { guarantee(*p == NULL || _bitmap->isMarked((HeapWord*) *p), "Should be marked"); } 2544 void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2545 } _oop_closure; 2546 public: 2547 VerifyKlassOopsKlassClosure(CMSBitMap* bitmap) : _oop_closure(bitmap) {} 2548 void do_klass(Klass* k) { 2549 k->oops_do(&_oop_closure); 2550 } 2551 }; 2552 2553 void CMSCollector::verify_after_remark_work_2() { 2554 ResourceMark rm; 2555 HandleMark hm; 2556 GenCollectedHeap* gch = GenCollectedHeap::heap(); 2557 2558 // Get a clear set of claim bits for the roots processing to work with. 2559 ClassLoaderDataGraph::clear_claimed_marks(); 2560 2561 // Mark from roots one level into CMS 2562 MarkRefsIntoVerifyClosure notOlder(_span, verification_mark_bm(), 2563 markBitMap()); 2564 CLDToOopClosure cld_closure(¬Older, true); 2565 2566 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel. 2567 2568 gch->gen_process_roots(_cmsGen->level(), 2569 true, // younger gens are roots 2570 true, // activate StrongRootsScope 2571 SharedHeap::ScanningOption(roots_scanning_options()), 2572 should_unload_classes(), 2573 ¬Older, 2574 NULL, 2575 &cld_closure); 2576 2577 // Now mark from the roots 2578 MarkFromRootsVerifyClosure markFromRootsClosure(this, _span, 2579 verification_mark_bm(), markBitMap(), verification_mark_stack()); 2580 assert(_restart_addr == NULL, "Expected pre-condition"); 2581 verification_mark_bm()->iterate(&markFromRootsClosure); 2582 while (_restart_addr != NULL) { 2583 // Deal with stack overflow: by restarting at the indicated 2584 // address. 2585 HeapWord* ra = _restart_addr; 2586 markFromRootsClosure.reset(ra); 2587 _restart_addr = NULL; 2588 verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end()); 2589 } 2590 assert(verification_mark_stack()->isEmpty(), "Should have been drained"); 2591 verify_work_stacks_empty(); 2592 2593 VerifyKlassOopsKlassClosure verify_klass_oops(verification_mark_bm()); 2594 ClassLoaderDataGraph::classes_do(&verify_klass_oops); 2595 2596 // Marking completed -- now verify that each bit marked in 2597 // verification_mark_bm() is also marked in markBitMap(); flag all 2598 // errors by printing corresponding objects. 2599 VerifyMarkedClosure vcl(markBitMap()); 2600 verification_mark_bm()->iterate(&vcl); 2601 assert(!vcl.failed(), "Else verification above should not have succeeded"); 2602 } 2603 2604 void ConcurrentMarkSweepGeneration::save_marks() { 2605 // delegate to CMS space 2606 cmsSpace()->save_marks(); 2607 for (uint i = 0; i < ParallelGCThreads; i++) { 2608 _par_gc_thread_states[i]->promo.startTrackingPromotions(); 2609 } 2610 } 2611 2612 bool ConcurrentMarkSweepGeneration::no_allocs_since_save_marks() { 2613 return cmsSpace()->no_allocs_since_save_marks(); 2614 } 2615 2616 #define CMS_SINCE_SAVE_MARKS_DEFN(OopClosureType, nv_suffix) \ 2617 \ 2618 void ConcurrentMarkSweepGeneration:: \ 2619 oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) { \ 2620 cl->set_generation(this); \ 2621 cmsSpace()->oop_since_save_marks_iterate##nv_suffix(cl); \ 2622 cl->reset_generation(); \ 2623 save_marks(); \ 2624 } 2625 2626 ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DEFN) 2627 2628 void 2629 ConcurrentMarkSweepGeneration::younger_refs_iterate(OopsInGenClosure* cl) { 2630 cl->set_generation(this); 2631 younger_refs_in_space_iterate(_cmsSpace, cl); 2632 cl->reset_generation(); 2633 } 2634 2635 void 2636 ConcurrentMarkSweepGeneration::oop_iterate(ExtendedOopClosure* cl) { 2637 if (freelistLock()->owned_by_self()) { 2638 Generation::oop_iterate(cl); 2639 } else { 2640 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 2641 Generation::oop_iterate(cl); 2642 } 2643 } 2644 2645 void 2646 ConcurrentMarkSweepGeneration::object_iterate(ObjectClosure* cl) { 2647 if (freelistLock()->owned_by_self()) { 2648 Generation::object_iterate(cl); 2649 } else { 2650 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 2651 Generation::object_iterate(cl); 2652 } 2653 } 2654 2655 void 2656 ConcurrentMarkSweepGeneration::safe_object_iterate(ObjectClosure* cl) { 2657 if (freelistLock()->owned_by_self()) { 2658 Generation::safe_object_iterate(cl); 2659 } else { 2660 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 2661 Generation::safe_object_iterate(cl); 2662 } 2663 } 2664 2665 void 2666 ConcurrentMarkSweepGeneration::post_compact() { 2667 } 2668 2669 void 2670 ConcurrentMarkSweepGeneration::prepare_for_verify() { 2671 // Fix the linear allocation blocks to look like free blocks. 2672 2673 // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those 2674 // are not called when the heap is verified during universe initialization and 2675 // at vm shutdown. 2676 if (freelistLock()->owned_by_self()) { 2677 cmsSpace()->prepare_for_verify(); 2678 } else { 2679 MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag); 2680 cmsSpace()->prepare_for_verify(); 2681 } 2682 } 2683 2684 void 2685 ConcurrentMarkSweepGeneration::verify() { 2686 // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those 2687 // are not called when the heap is verified during universe initialization and 2688 // at vm shutdown. 2689 if (freelistLock()->owned_by_self()) { 2690 cmsSpace()->verify(); 2691 } else { 2692 MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag); 2693 cmsSpace()->verify(); 2694 } 2695 } 2696 2697 void CMSCollector::verify() { 2698 _cmsGen->verify(); 2699 } 2700 2701 #ifndef PRODUCT 2702 bool CMSCollector::overflow_list_is_empty() const { 2703 assert(_num_par_pushes >= 0, "Inconsistency"); 2704 if (_overflow_list == NULL) { 2705 assert(_num_par_pushes == 0, "Inconsistency"); 2706 } 2707 return _overflow_list == NULL; 2708 } 2709 2710 // The methods verify_work_stacks_empty() and verify_overflow_empty() 2711 // merely consolidate assertion checks that appear to occur together frequently. 2712 void CMSCollector::verify_work_stacks_empty() const { 2713 assert(_markStack.isEmpty(), "Marking stack should be empty"); 2714 assert(overflow_list_is_empty(), "Overflow list should be empty"); 2715 } 2716 2717 void CMSCollector::verify_overflow_empty() const { 2718 assert(overflow_list_is_empty(), "Overflow list should be empty"); 2719 assert(no_preserved_marks(), "No preserved marks"); 2720 } 2721 #endif // PRODUCT 2722 2723 // Decide if we want to enable class unloading as part of the 2724 // ensuing concurrent GC cycle. We will collect and 2725 // unload classes if it's the case that: 2726 // (1) an explicit gc request has been made and the flag 2727 // ExplicitGCInvokesConcurrentAndUnloadsClasses is set, OR 2728 // (2) (a) class unloading is enabled at the command line, and 2729 // (b) old gen is getting really full 2730 // NOTE: Provided there is no change in the state of the heap between 2731 // calls to this method, it should have idempotent results. Moreover, 2732 // its results should be monotonically increasing (i.e. going from 0 to 1, 2733 // but not 1 to 0) between successive calls between which the heap was 2734 // not collected. For the implementation below, it must thus rely on 2735 // the property that concurrent_cycles_since_last_unload() 2736 // will not decrease unless a collection cycle happened and that 2737 // _cmsGen->is_too_full() are 2738 // themselves also monotonic in that sense. See check_monotonicity() 2739 // below. 2740 void CMSCollector::update_should_unload_classes() { 2741 _should_unload_classes = false; 2742 // Condition 1 above 2743 if (_full_gc_requested && ExplicitGCInvokesConcurrentAndUnloadsClasses) { 2744 _should_unload_classes = true; 2745 } else if (CMSClassUnloadingEnabled) { // Condition 2.a above 2746 // Disjuncts 2.b.(i,ii,iii) above 2747 _should_unload_classes = (concurrent_cycles_since_last_unload() >= 2748 CMSClassUnloadingMaxInterval) 2749 || _cmsGen->is_too_full(); 2750 } 2751 } 2752 2753 bool ConcurrentMarkSweepGeneration::is_too_full() const { 2754 bool res = should_concurrent_collect(); 2755 res = res && (occupancy() > (double)CMSIsTooFullPercentage/100.0); 2756 return res; 2757 } 2758 2759 void CMSCollector::setup_cms_unloading_and_verification_state() { 2760 const bool should_verify = VerifyBeforeGC || VerifyAfterGC || VerifyDuringGC 2761 || VerifyBeforeExit; 2762 const int rso = SharedHeap::SO_AllCodeCache; 2763 2764 // We set the proper root for this CMS cycle here. 2765 if (should_unload_classes()) { // Should unload classes this cycle 2766 remove_root_scanning_option(rso); // Shrink the root set appropriately 2767 set_verifying(should_verify); // Set verification state for this cycle 2768 return; // Nothing else needs to be done at this time 2769 } 2770 2771 // Not unloading classes this cycle 2772 assert(!should_unload_classes(), "Inconsistency!"); 2773 2774 if ((!verifying() || unloaded_classes_last_cycle()) && should_verify) { 2775 // Include symbols, strings and code cache elements to prevent their resurrection. 2776 add_root_scanning_option(rso); 2777 set_verifying(true); 2778 } else if (verifying() && !should_verify) { 2779 // We were verifying, but some verification flags got disabled. 2780 set_verifying(false); 2781 // Exclude symbols, strings and code cache elements from root scanning to 2782 // reduce IM and RM pauses. 2783 remove_root_scanning_option(rso); 2784 } 2785 } 2786 2787 2788 #ifndef PRODUCT 2789 HeapWord* CMSCollector::block_start(const void* p) const { 2790 const HeapWord* addr = (HeapWord*)p; 2791 if (_span.contains(p)) { 2792 if (_cmsGen->cmsSpace()->is_in_reserved(addr)) { 2793 return _cmsGen->cmsSpace()->block_start(p); 2794 } 2795 } 2796 return NULL; 2797 } 2798 #endif 2799 2800 HeapWord* 2801 ConcurrentMarkSweepGeneration::expand_and_allocate(size_t word_size, 2802 bool tlab, 2803 bool parallel) { 2804 CMSSynchronousYieldRequest yr; 2805 assert(!tlab, "Can't deal with TLAB allocation"); 2806 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 2807 expand(word_size*HeapWordSize, MinHeapDeltaBytes, 2808 CMSExpansionCause::_satisfy_allocation); 2809 if (GCExpandToAllocateDelayMillis > 0) { 2810 os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false); 2811 } 2812 return have_lock_and_allocate(word_size, tlab); 2813 } 2814 2815 // YSR: All of this generation expansion/shrinking stuff is an exact copy of 2816 // TenuredGeneration, which makes me wonder if we should move this 2817 // to CardGeneration and share it... 2818 bool ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes) { 2819 return CardGeneration::expand(bytes, expand_bytes); 2820 } 2821 2822 void ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes, 2823 CMSExpansionCause::Cause cause) 2824 { 2825 2826 bool success = expand(bytes, expand_bytes); 2827 2828 // remember why we expanded; this information is used 2829 // by shouldConcurrentCollect() when making decisions on whether to start 2830 // a new CMS cycle. 2831 if (success) { 2832 set_expansion_cause(cause); 2833 if (PrintGCDetails && Verbose) { 2834 gclog_or_tty->print_cr("Expanded CMS gen for %s", 2835 CMSExpansionCause::to_string(cause)); 2836 } 2837 } 2838 } 2839 2840 HeapWord* ConcurrentMarkSweepGeneration::expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz) { 2841 HeapWord* res = NULL; 2842 MutexLocker x(ParGCRareEvent_lock); 2843 while (true) { 2844 // Expansion by some other thread might make alloc OK now: 2845 res = ps->lab.alloc(word_sz); 2846 if (res != NULL) return res; 2847 // If there's not enough expansion space available, give up. 2848 if (_virtual_space.uncommitted_size() < (word_sz * HeapWordSize)) { 2849 return NULL; 2850 } 2851 // Otherwise, we try expansion. 2852 expand(word_sz*HeapWordSize, MinHeapDeltaBytes, 2853 CMSExpansionCause::_allocate_par_lab); 2854 // Now go around the loop and try alloc again; 2855 // A competing par_promote might beat us to the expansion space, 2856 // so we may go around the loop again if promotion fails again. 2857 if (GCExpandToAllocateDelayMillis > 0) { 2858 os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false); 2859 } 2860 } 2861 } 2862 2863 2864 bool ConcurrentMarkSweepGeneration::expand_and_ensure_spooling_space( 2865 PromotionInfo* promo) { 2866 MutexLocker x(ParGCRareEvent_lock); 2867 size_t refill_size_bytes = promo->refillSize() * HeapWordSize; 2868 while (true) { 2869 // Expansion by some other thread might make alloc OK now: 2870 if (promo->ensure_spooling_space()) { 2871 assert(promo->has_spooling_space(), 2872 "Post-condition of successful ensure_spooling_space()"); 2873 return true; 2874 } 2875 // If there's not enough expansion space available, give up. 2876 if (_virtual_space.uncommitted_size() < refill_size_bytes) { 2877 return false; 2878 } 2879 // Otherwise, we try expansion. 2880 expand(refill_size_bytes, MinHeapDeltaBytes, 2881 CMSExpansionCause::_allocate_par_spooling_space); 2882 // Now go around the loop and try alloc again; 2883 // A competing allocation might beat us to the expansion space, 2884 // so we may go around the loop again if allocation fails again. 2885 if (GCExpandToAllocateDelayMillis > 0) { 2886 os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false); 2887 } 2888 } 2889 } 2890 2891 2892 void ConcurrentMarkSweepGeneration::shrink_by(size_t bytes) { 2893 assert_locked_or_safepoint(ExpandHeap_lock); 2894 // Shrink committed space 2895 _virtual_space.shrink_by(bytes); 2896 // Shrink space; this also shrinks the space's BOT 2897 _cmsSpace->set_end((HeapWord*) _virtual_space.high()); 2898 size_t new_word_size = heap_word_size(_cmsSpace->capacity()); 2899 // Shrink the shared block offset array 2900 _bts->resize(new_word_size); 2901 MemRegion mr(_cmsSpace->bottom(), new_word_size); 2902 // Shrink the card table 2903 Universe::heap()->barrier_set()->resize_covered_region(mr); 2904 2905 if (Verbose && PrintGC) { 2906 size_t new_mem_size = _virtual_space.committed_size(); 2907 size_t old_mem_size = new_mem_size + bytes; 2908 gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K to " SIZE_FORMAT "K", 2909 name(), old_mem_size/K, new_mem_size/K); 2910 } 2911 } 2912 2913 void ConcurrentMarkSweepGeneration::shrink(size_t bytes) { 2914 assert_locked_or_safepoint(Heap_lock); 2915 size_t size = ReservedSpace::page_align_size_down(bytes); 2916 // Only shrink if a compaction was done so that all the free space 2917 // in the generation is in a contiguous block at the end. 2918 if (size > 0 && did_compact()) { 2919 shrink_by(size); 2920 } 2921 } 2922 2923 bool ConcurrentMarkSweepGeneration::grow_by(size_t bytes) { 2924 assert_locked_or_safepoint(Heap_lock); 2925 bool result = _virtual_space.expand_by(bytes); 2926 if (result) { 2927 size_t new_word_size = 2928 heap_word_size(_virtual_space.committed_size()); 2929 MemRegion mr(_cmsSpace->bottom(), new_word_size); 2930 _bts->resize(new_word_size); // resize the block offset shared array 2931 Universe::heap()->barrier_set()->resize_covered_region(mr); 2932 // Hmmmm... why doesn't CFLS::set_end verify locking? 2933 // This is quite ugly; FIX ME XXX 2934 _cmsSpace->assert_locked(freelistLock()); 2935 _cmsSpace->set_end((HeapWord*)_virtual_space.high()); 2936 2937 // update the space and generation capacity counters 2938 if (UsePerfData) { 2939 _space_counters->update_capacity(); 2940 _gen_counters->update_all(); 2941 } 2942 2943 if (Verbose && PrintGC) { 2944 size_t new_mem_size = _virtual_space.committed_size(); 2945 size_t old_mem_size = new_mem_size - bytes; 2946 gclog_or_tty->print_cr("Expanding %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K", 2947 name(), old_mem_size/K, bytes/K, new_mem_size/K); 2948 } 2949 } 2950 return result; 2951 } 2952 2953 bool ConcurrentMarkSweepGeneration::grow_to_reserved() { 2954 assert_locked_or_safepoint(Heap_lock); 2955 bool success = true; 2956 const size_t remaining_bytes = _virtual_space.uncommitted_size(); 2957 if (remaining_bytes > 0) { 2958 success = grow_by(remaining_bytes); 2959 DEBUG_ONLY(if (!success) warning("grow to reserved failed");) 2960 } 2961 return success; 2962 } 2963 2964 void ConcurrentMarkSweepGeneration::shrink_free_list_by(size_t bytes) { 2965 assert_locked_or_safepoint(Heap_lock); 2966 assert_lock_strong(freelistLock()); 2967 if (PrintGCDetails && Verbose) { 2968 warning("Shrinking of CMS not yet implemented"); 2969 } 2970 return; 2971 } 2972 2973 2974 // Simple ctor/dtor wrapper for accounting & timer chores around concurrent 2975 // phases. 2976 class CMSPhaseAccounting: public StackObj { 2977 public: 2978 CMSPhaseAccounting(CMSCollector *collector, 2979 const char *phase, 2980 const GCId gc_id, 2981 bool print_cr = true); 2982 ~CMSPhaseAccounting(); 2983 2984 private: 2985 CMSCollector *_collector; 2986 const char *_phase; 2987 elapsedTimer _wallclock; 2988 bool _print_cr; 2989 const GCId _gc_id; 2990 2991 public: 2992 // Not MT-safe; so do not pass around these StackObj's 2993 // where they may be accessed by other threads. 2994 jlong wallclock_millis() { 2995 assert(_wallclock.is_active(), "Wall clock should not stop"); 2996 _wallclock.stop(); // to record time 2997 jlong ret = _wallclock.milliseconds(); 2998 _wallclock.start(); // restart 2999 return ret; 3000 } 3001 }; 3002 3003 CMSPhaseAccounting::CMSPhaseAccounting(CMSCollector *collector, 3004 const char *phase, 3005 const GCId gc_id, 3006 bool print_cr) : 3007 _collector(collector), _phase(phase), _print_cr(print_cr), _gc_id(gc_id) { 3008 3009 if (PrintCMSStatistics != 0) { 3010 _collector->resetYields(); 3011 } 3012 if (PrintGCDetails) { 3013 gclog_or_tty->gclog_stamp(_gc_id); 3014 gclog_or_tty->print_cr("[%s-concurrent-%s-start]", 3015 _collector->cmsGen()->short_name(), _phase); 3016 } 3017 _collector->resetTimer(); 3018 _wallclock.start(); 3019 _collector->startTimer(); 3020 } 3021 3022 CMSPhaseAccounting::~CMSPhaseAccounting() { 3023 assert(_wallclock.is_active(), "Wall clock should not have stopped"); 3024 _collector->stopTimer(); 3025 _wallclock.stop(); 3026 if (PrintGCDetails) { 3027 gclog_or_tty->gclog_stamp(_gc_id); 3028 gclog_or_tty->print("[%s-concurrent-%s: %3.3f/%3.3f secs]", 3029 _collector->cmsGen()->short_name(), 3030 _phase, _collector->timerValue(), _wallclock.seconds()); 3031 if (_print_cr) { 3032 gclog_or_tty->cr(); 3033 } 3034 if (PrintCMSStatistics != 0) { 3035 gclog_or_tty->print_cr(" (CMS-concurrent-%s yielded %d times)", _phase, 3036 _collector->yields()); 3037 } 3038 } 3039 } 3040 3041 // CMS work 3042 3043 // The common parts of CMSParInitialMarkTask and CMSParRemarkTask. 3044 class CMSParMarkTask : public AbstractGangTask { 3045 protected: 3046 CMSCollector* _collector; 3047 int _n_workers; 3048 CMSParMarkTask(const char* name, CMSCollector* collector, int n_workers) : 3049 AbstractGangTask(name), 3050 _collector(collector), 3051 _n_workers(n_workers) {} 3052 // Work method in support of parallel rescan ... of young gen spaces 3053 void do_young_space_rescan(uint worker_id, OopsInGenClosure* cl, 3054 ContiguousSpace* space, 3055 HeapWord** chunk_array, size_t chunk_top); 3056 void work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl); 3057 }; 3058 3059 // Parallel initial mark task 3060 class CMSParInitialMarkTask: public CMSParMarkTask { 3061 public: 3062 CMSParInitialMarkTask(CMSCollector* collector, int n_workers) : 3063 CMSParMarkTask("Scan roots and young gen for initial mark in parallel", 3064 collector, n_workers) {} 3065 void work(uint worker_id); 3066 }; 3067 3068 // Checkpoint the roots into this generation from outside 3069 // this generation. [Note this initial checkpoint need only 3070 // be approximate -- we'll do a catch up phase subsequently.] 3071 void CMSCollector::checkpointRootsInitial() { 3072 assert(_collectorState == InitialMarking, "Wrong collector state"); 3073 check_correct_thread_executing(); 3074 TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause()); 3075 3076 save_heap_summary(); 3077 report_heap_summary(GCWhen::BeforeGC); 3078 3079 ReferenceProcessor* rp = ref_processor(); 3080 SpecializationStats::clear(); 3081 assert(_restart_addr == NULL, "Control point invariant"); 3082 { 3083 // acquire locks for subsequent manipulations 3084 MutexLockerEx x(bitMapLock(), 3085 Mutex::_no_safepoint_check_flag); 3086 checkpointRootsInitialWork(); 3087 // enable ("weak") refs discovery 3088 rp->enable_discovery(true /*verify_disabled*/, true /*check_no_refs*/); 3089 _collectorState = Marking; 3090 } 3091 SpecializationStats::print(); 3092 } 3093 3094 void CMSCollector::checkpointRootsInitialWork() { 3095 assert(SafepointSynchronize::is_at_safepoint(), "world should be stopped"); 3096 assert(_collectorState == InitialMarking, "just checking"); 3097 3098 // If there has not been a GC[n-1] since last GC[n] cycle completed, 3099 // precede our marking with a collection of all 3100 // younger generations to keep floating garbage to a minimum. 3101 // XXX: we won't do this for now -- it's an optimization to be done later. 3102 3103 // already have locks 3104 assert_lock_strong(bitMapLock()); 3105 assert(_markBitMap.isAllClear(), "was reset at end of previous cycle"); 3106 3107 // Setup the verification and class unloading state for this 3108 // CMS collection cycle. 3109 setup_cms_unloading_and_verification_state(); 3110 3111 NOT_PRODUCT(GCTraceTime t("\ncheckpointRootsInitialWork", 3112 PrintGCDetails && Verbose, true, _gc_timer_cm, _gc_tracer_cm->gc_id());) 3113 3114 // Reset all the PLAB chunk arrays if necessary. 3115 if (_survivor_plab_array != NULL && !CMSPLABRecordAlways) { 3116 reset_survivor_plab_arrays(); 3117 } 3118 3119 ResourceMark rm; 3120 HandleMark hm; 3121 3122 MarkRefsIntoClosure notOlder(_span, &_markBitMap); 3123 GenCollectedHeap* gch = GenCollectedHeap::heap(); 3124 3125 verify_work_stacks_empty(); 3126 verify_overflow_empty(); 3127 3128 gch->ensure_parsability(false); // fill TLABs, but no need to retire them 3129 // Update the saved marks which may affect the root scans. 3130 gch->save_marks(); 3131 3132 // weak reference processing has not started yet. 3133 ref_processor()->set_enqueuing_is_done(false); 3134 3135 // Need to remember all newly created CLDs, 3136 // so that we can guarantee that the remark finds them. 3137 ClassLoaderDataGraph::remember_new_clds(true); 3138 3139 // Whenever a CLD is found, it will be claimed before proceeding to mark 3140 // the klasses. The claimed marks need to be cleared before marking starts. 3141 ClassLoaderDataGraph::clear_claimed_marks(); 3142 3143 if (CMSPrintEdenSurvivorChunks) { 3144 print_eden_and_survivor_chunk_arrays(); 3145 } 3146 3147 { 3148 COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;) 3149 if (CMSParallelInitialMarkEnabled && CollectedHeap::use_parallel_gc_threads()) { 3150 // The parallel version. 3151 FlexibleWorkGang* workers = gch->workers(); 3152 assert(workers != NULL, "Need parallel worker threads."); 3153 int n_workers = workers->active_workers(); 3154 CMSParInitialMarkTask tsk(this, n_workers); 3155 gch->set_par_threads(n_workers); 3156 initialize_sequential_subtasks_for_young_gen_rescan(n_workers); 3157 if (n_workers > 1) { 3158 GenCollectedHeap::StrongRootsScope srs(gch); 3159 workers->run_task(&tsk); 3160 } else { 3161 GenCollectedHeap::StrongRootsScope srs(gch); 3162 tsk.work(0); 3163 } 3164 gch->set_par_threads(0); 3165 } else { 3166 // The serial version. 3167 CLDToOopClosure cld_closure(¬Older, true); 3168 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel. 3169 gch->gen_process_roots(_cmsGen->level(), 3170 true, // younger gens are roots 3171 true, // activate StrongRootsScope 3172 SharedHeap::ScanningOption(roots_scanning_options()), 3173 should_unload_classes(), 3174 ¬Older, 3175 NULL, 3176 &cld_closure); 3177 } 3178 } 3179 3180 // Clear mod-union table; it will be dirtied in the prologue of 3181 // CMS generation per each younger generation collection. 3182 3183 assert(_modUnionTable.isAllClear(), 3184 "Was cleared in most recent final checkpoint phase" 3185 " or no bits are set in the gc_prologue before the start of the next " 3186 "subsequent marking phase."); 3187 3188 assert(_ct->klass_rem_set()->mod_union_is_clear(), "Must be"); 3189 3190 // Save the end of the used_region of the constituent generations 3191 // to be used to limit the extent of sweep in each generation. 3192 save_sweep_limits(); 3193 verify_overflow_empty(); 3194 } 3195 3196 bool CMSCollector::markFromRoots() { 3197 // we might be tempted to assert that: 3198 // assert(!SafepointSynchronize::is_at_safepoint(), 3199 // "inconsistent argument?"); 3200 // However that wouldn't be right, because it's possible that 3201 // a safepoint is indeed in progress as a younger generation 3202 // stop-the-world GC happens even as we mark in this generation. 3203 assert(_collectorState == Marking, "inconsistent state?"); 3204 check_correct_thread_executing(); 3205 verify_overflow_empty(); 3206 3207 // Weak ref discovery note: We may be discovering weak 3208 // refs in this generation concurrent (but interleaved) with 3209 // weak ref discovery by a younger generation collector. 3210 3211 CMSTokenSyncWithLocks ts(true, bitMapLock()); 3212 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 3213 CMSPhaseAccounting pa(this, "mark", _gc_tracer_cm->gc_id(), !PrintGCDetails); 3214 bool res = markFromRootsWork(); 3215 if (res) { 3216 _collectorState = Precleaning; 3217 } else { // We failed and a foreground collection wants to take over 3218 assert(_foregroundGCIsActive, "internal state inconsistency"); 3219 assert(_restart_addr == NULL, "foreground will restart from scratch"); 3220 if (PrintGCDetails) { 3221 gclog_or_tty->print_cr("bailing out to foreground collection"); 3222 } 3223 } 3224 verify_overflow_empty(); 3225 return res; 3226 } 3227 3228 bool CMSCollector::markFromRootsWork() { 3229 // iterate over marked bits in bit map, doing a full scan and mark 3230 // from these roots using the following algorithm: 3231 // . if oop is to the right of the current scan pointer, 3232 // mark corresponding bit (we'll process it later) 3233 // . else (oop is to left of current scan pointer) 3234 // push oop on marking stack 3235 // . drain the marking stack 3236 3237 // Note that when we do a marking step we need to hold the 3238 // bit map lock -- recall that direct allocation (by mutators) 3239 // and promotion (by younger generation collectors) is also 3240 // marking the bit map. [the so-called allocate live policy.] 3241 // Because the implementation of bit map marking is not 3242 // robust wrt simultaneous marking of bits in the same word, 3243 // we need to make sure that there is no such interference 3244 // between concurrent such updates. 3245 3246 // already have locks 3247 assert_lock_strong(bitMapLock()); 3248 3249 verify_work_stacks_empty(); 3250 verify_overflow_empty(); 3251 bool result = false; 3252 if (CMSConcurrentMTEnabled && ConcGCThreads > 0) { 3253 result = do_marking_mt(); 3254 } else { 3255 result = do_marking_st(); 3256 } 3257 return result; 3258 } 3259 3260 // Forward decl 3261 class CMSConcMarkingTask; 3262 3263 class CMSConcMarkingTerminator: public ParallelTaskTerminator { 3264 CMSCollector* _collector; 3265 CMSConcMarkingTask* _task; 3266 public: 3267 virtual void yield(); 3268 3269 // "n_threads" is the number of threads to be terminated. 3270 // "queue_set" is a set of work queues of other threads. 3271 // "collector" is the CMS collector associated with this task terminator. 3272 // "yield" indicates whether we need the gang as a whole to yield. 3273 CMSConcMarkingTerminator(int n_threads, TaskQueueSetSuper* queue_set, CMSCollector* collector) : 3274 ParallelTaskTerminator(n_threads, queue_set), 3275 _collector(collector) { } 3276 3277 void set_task(CMSConcMarkingTask* task) { 3278 _task = task; 3279 } 3280 }; 3281 3282 class CMSConcMarkingTerminatorTerminator: public TerminatorTerminator { 3283 CMSConcMarkingTask* _task; 3284 public: 3285 bool should_exit_termination(); 3286 void set_task(CMSConcMarkingTask* task) { 3287 _task = task; 3288 } 3289 }; 3290 3291 // MT Concurrent Marking Task 3292 class CMSConcMarkingTask: public YieldingFlexibleGangTask { 3293 CMSCollector* _collector; 3294 int _n_workers; // requested/desired # workers 3295 bool _result; 3296 CompactibleFreeListSpace* _cms_space; 3297 char _pad_front[64]; // padding to ... 3298 HeapWord* _global_finger; // ... avoid sharing cache line 3299 char _pad_back[64]; 3300 HeapWord* _restart_addr; 3301 3302 // Exposed here for yielding support 3303 Mutex* const _bit_map_lock; 3304 3305 // The per thread work queues, available here for stealing 3306 OopTaskQueueSet* _task_queues; 3307 3308 // Termination (and yielding) support 3309 CMSConcMarkingTerminator _term; 3310 CMSConcMarkingTerminatorTerminator _term_term; 3311 3312 public: 3313 CMSConcMarkingTask(CMSCollector* collector, 3314 CompactibleFreeListSpace* cms_space, 3315 YieldingFlexibleWorkGang* workers, 3316 OopTaskQueueSet* task_queues): 3317 YieldingFlexibleGangTask("Concurrent marking done multi-threaded"), 3318 _collector(collector), 3319 _cms_space(cms_space), 3320 _n_workers(0), _result(true), 3321 _task_queues(task_queues), 3322 _term(_n_workers, task_queues, _collector), 3323 _bit_map_lock(collector->bitMapLock()) 3324 { 3325 _requested_size = _n_workers; 3326 _term.set_task(this); 3327 _term_term.set_task(this); 3328 _restart_addr = _global_finger = _cms_space->bottom(); 3329 } 3330 3331 3332 OopTaskQueueSet* task_queues() { return _task_queues; } 3333 3334 OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); } 3335 3336 HeapWord** global_finger_addr() { return &_global_finger; } 3337 3338 CMSConcMarkingTerminator* terminator() { return &_term; } 3339 3340 virtual void set_for_termination(int active_workers) { 3341 terminator()->reset_for_reuse(active_workers); 3342 } 3343 3344 void work(uint worker_id); 3345 bool should_yield() { 3346 return ConcurrentMarkSweepThread::should_yield() 3347 && !_collector->foregroundGCIsActive(); 3348 } 3349 3350 virtual void coordinator_yield(); // stuff done by coordinator 3351 bool result() { return _result; } 3352 3353 void reset(HeapWord* ra) { 3354 assert(_global_finger >= _cms_space->end(), "Postcondition of ::work(i)"); 3355 _restart_addr = _global_finger = ra; 3356 _term.reset_for_reuse(); 3357 } 3358 3359 static bool get_work_from_overflow_stack(CMSMarkStack* ovflw_stk, 3360 OopTaskQueue* work_q); 3361 3362 private: 3363 void do_scan_and_mark(int i, CompactibleFreeListSpace* sp); 3364 void do_work_steal(int i); 3365 void bump_global_finger(HeapWord* f); 3366 }; 3367 3368 bool CMSConcMarkingTerminatorTerminator::should_exit_termination() { 3369 assert(_task != NULL, "Error"); 3370 return _task->yielding(); 3371 // Note that we do not need the disjunct || _task->should_yield() above 3372 // because we want terminating threads to yield only if the task 3373 // is already in the midst of yielding, which happens only after at least one 3374 // thread has yielded. 3375 } 3376 3377 void CMSConcMarkingTerminator::yield() { 3378 if (_task->should_yield()) { 3379 _task->yield(); 3380 } else { 3381 ParallelTaskTerminator::yield(); 3382 } 3383 } 3384 3385 //////////////////////////////////////////////////////////////// 3386 // Concurrent Marking Algorithm Sketch 3387 //////////////////////////////////////////////////////////////// 3388 // Until all tasks exhausted (both spaces): 3389 // -- claim next available chunk 3390 // -- bump global finger via CAS 3391 // -- find first object that starts in this chunk 3392 // and start scanning bitmap from that position 3393 // -- scan marked objects for oops 3394 // -- CAS-mark target, and if successful: 3395 // . if target oop is above global finger (volatile read) 3396 // nothing to do 3397 // . if target oop is in chunk and above local finger 3398 // then nothing to do 3399 // . else push on work-queue 3400 // -- Deal with possible overflow issues: 3401 // . local work-queue overflow causes stuff to be pushed on 3402 // global (common) overflow queue 3403 // . always first empty local work queue 3404 // . then get a batch of oops from global work queue if any 3405 // . then do work stealing 3406 // -- When all tasks claimed (both spaces) 3407 // and local work queue empty, 3408 // then in a loop do: 3409 // . check global overflow stack; steal a batch of oops and trace 3410 // . try to steal from other threads oif GOS is empty 3411 // . if neither is available, offer termination 3412 // -- Terminate and return result 3413 // 3414 void CMSConcMarkingTask::work(uint worker_id) { 3415 elapsedTimer _timer; 3416 ResourceMark rm; 3417 HandleMark hm; 3418 3419 DEBUG_ONLY(_collector->verify_overflow_empty();) 3420 3421 // Before we begin work, our work queue should be empty 3422 assert(work_queue(worker_id)->size() == 0, "Expected to be empty"); 3423 // Scan the bitmap covering _cms_space, tracing through grey objects. 3424 _timer.start(); 3425 do_scan_and_mark(worker_id, _cms_space); 3426 _timer.stop(); 3427 if (PrintCMSStatistics != 0) { 3428 gclog_or_tty->print_cr("Finished cms space scanning in %dth thread: %3.3f sec", 3429 worker_id, _timer.seconds()); 3430 // XXX: need xxx/xxx type of notation, two timers 3431 } 3432 3433 // ... do work stealing 3434 _timer.reset(); 3435 _timer.start(); 3436 do_work_steal(worker_id); 3437 _timer.stop(); 3438 if (PrintCMSStatistics != 0) { 3439 gclog_or_tty->print_cr("Finished work stealing in %dth thread: %3.3f sec", 3440 worker_id, _timer.seconds()); 3441 // XXX: need xxx/xxx type of notation, two timers 3442 } 3443 assert(_collector->_markStack.isEmpty(), "Should have been emptied"); 3444 assert(work_queue(worker_id)->size() == 0, "Should have been emptied"); 3445 // Note that under the current task protocol, the 3446 // following assertion is true even of the spaces 3447 // expanded since the completion of the concurrent 3448 // marking. XXX This will likely change under a strict 3449 // ABORT semantics. 3450 // After perm removal the comparison was changed to 3451 // greater than or equal to from strictly greater than. 3452 // Before perm removal the highest address sweep would 3453 // have been at the end of perm gen but now is at the 3454 // end of the tenured gen. 3455 assert(_global_finger >= _cms_space->end(), 3456 "All tasks have been completed"); 3457 DEBUG_ONLY(_collector->verify_overflow_empty();) 3458 } 3459 3460 void CMSConcMarkingTask::bump_global_finger(HeapWord* f) { 3461 HeapWord* read = _global_finger; 3462 HeapWord* cur = read; 3463 while (f > read) { 3464 cur = read; 3465 read = (HeapWord*) Atomic::cmpxchg_ptr(f, &_global_finger, cur); 3466 if (cur == read) { 3467 // our cas succeeded 3468 assert(_global_finger >= f, "protocol consistency"); 3469 break; 3470 } 3471 } 3472 } 3473 3474 // This is really inefficient, and should be redone by 3475 // using (not yet available) block-read and -write interfaces to the 3476 // stack and the work_queue. XXX FIX ME !!! 3477 bool CMSConcMarkingTask::get_work_from_overflow_stack(CMSMarkStack* ovflw_stk, 3478 OopTaskQueue* work_q) { 3479 // Fast lock-free check 3480 if (ovflw_stk->length() == 0) { 3481 return false; 3482 } 3483 assert(work_q->size() == 0, "Shouldn't steal"); 3484 MutexLockerEx ml(ovflw_stk->par_lock(), 3485 Mutex::_no_safepoint_check_flag); 3486 // Grab up to 1/4 the size of the work queue 3487 size_t num = MIN2((size_t)(work_q->max_elems() - work_q->size())/4, 3488 (size_t)ParGCDesiredObjsFromOverflowList); 3489 num = MIN2(num, ovflw_stk->length()); 3490 for (int i = (int) num; i > 0; i--) { 3491 oop cur = ovflw_stk->pop(); 3492 assert(cur != NULL, "Counted wrong?"); 3493 work_q->push(cur); 3494 } 3495 return num > 0; 3496 } 3497 3498 void CMSConcMarkingTask::do_scan_and_mark(int i, CompactibleFreeListSpace* sp) { 3499 SequentialSubTasksDone* pst = sp->conc_par_seq_tasks(); 3500 int n_tasks = pst->n_tasks(); 3501 // We allow that there may be no tasks to do here because 3502 // we are restarting after a stack overflow. 3503 assert(pst->valid() || n_tasks == 0, "Uninitialized use?"); 3504 uint nth_task = 0; 3505 3506 HeapWord* aligned_start = sp->bottom(); 3507 if (sp->used_region().contains(_restart_addr)) { 3508 // Align down to a card boundary for the start of 0th task 3509 // for this space. 3510 aligned_start = 3511 (HeapWord*)align_size_down((uintptr_t)_restart_addr, 3512 CardTableModRefBS::card_size); 3513 } 3514 3515 size_t chunk_size = sp->marking_task_size(); 3516 while (!pst->is_task_claimed(/* reference */ nth_task)) { 3517 // Having claimed the nth task in this space, 3518 // compute the chunk that it corresponds to: 3519 MemRegion span = MemRegion(aligned_start + nth_task*chunk_size, 3520 aligned_start + (nth_task+1)*chunk_size); 3521 // Try and bump the global finger via a CAS; 3522 // note that we need to do the global finger bump 3523 // _before_ taking the intersection below, because 3524 // the task corresponding to that region will be 3525 // deemed done even if the used_region() expands 3526 // because of allocation -- as it almost certainly will 3527 // during start-up while the threads yield in the 3528 // closure below. 3529 HeapWord* finger = span.end(); 3530 bump_global_finger(finger); // atomically 3531 // There are null tasks here corresponding to chunks 3532 // beyond the "top" address of the space. 3533 span = span.intersection(sp->used_region()); 3534 if (!span.is_empty()) { // Non-null task 3535 HeapWord* prev_obj; 3536 assert(!span.contains(_restart_addr) || nth_task == 0, 3537 "Inconsistency"); 3538 if (nth_task == 0) { 3539 // For the 0th task, we'll not need to compute a block_start. 3540 if (span.contains(_restart_addr)) { 3541 // In the case of a restart because of stack overflow, 3542 // we might additionally skip a chunk prefix. 3543 prev_obj = _restart_addr; 3544 } else { 3545 prev_obj = span.start(); 3546 } 3547 } else { 3548 // We want to skip the first object because 3549 // the protocol is to scan any object in its entirety 3550 // that _starts_ in this span; a fortiori, any 3551 // object starting in an earlier span is scanned 3552 // as part of an earlier claimed task. 3553 // Below we use the "careful" version of block_start 3554 // so we do not try to navigate uninitialized objects. 3555 prev_obj = sp->block_start_careful(span.start()); 3556 // Below we use a variant of block_size that uses the 3557 // Printezis bits to avoid waiting for allocated 3558 // objects to become initialized/parsable. 3559 while (prev_obj < span.start()) { 3560 size_t sz = sp->block_size_no_stall(prev_obj, _collector); 3561 if (sz > 0) { 3562 prev_obj += sz; 3563 } else { 3564 // In this case we may end up doing a bit of redundant 3565 // scanning, but that appears unavoidable, short of 3566 // locking the free list locks; see bug 6324141. 3567 break; 3568 } 3569 } 3570 } 3571 if (prev_obj < span.end()) { 3572 MemRegion my_span = MemRegion(prev_obj, span.end()); 3573 // Do the marking work within a non-empty span -- 3574 // the last argument to the constructor indicates whether the 3575 // iteration should be incremental with periodic yields. 3576 Par_MarkFromRootsClosure cl(this, _collector, my_span, 3577 &_collector->_markBitMap, 3578 work_queue(i), 3579 &_collector->_markStack); 3580 _collector->_markBitMap.iterate(&cl, my_span.start(), my_span.end()); 3581 } // else nothing to do for this task 3582 } // else nothing to do for this task 3583 } 3584 // We'd be tempted to assert here that since there are no 3585 // more tasks left to claim in this space, the global_finger 3586 // must exceed space->top() and a fortiori space->end(). However, 3587 // that would not quite be correct because the bumping of 3588 // global_finger occurs strictly after the claiming of a task, 3589 // so by the time we reach here the global finger may not yet 3590 // have been bumped up by the thread that claimed the last 3591 // task. 3592 pst->all_tasks_completed(); 3593 } 3594 3595 class Par_ConcMarkingClosure: public MetadataAwareOopClosure { 3596 private: 3597 CMSCollector* _collector; 3598 CMSConcMarkingTask* _task; 3599 MemRegion _span; 3600 CMSBitMap* _bit_map; 3601 CMSMarkStack* _overflow_stack; 3602 OopTaskQueue* _work_queue; 3603 protected: 3604 DO_OOP_WORK_DEFN 3605 public: 3606 Par_ConcMarkingClosure(CMSCollector* collector, CMSConcMarkingTask* task, OopTaskQueue* work_queue, 3607 CMSBitMap* bit_map, CMSMarkStack* overflow_stack): 3608 MetadataAwareOopClosure(collector->ref_processor()), 3609 _collector(collector), 3610 _task(task), 3611 _span(collector->_span), 3612 _work_queue(work_queue), 3613 _bit_map(bit_map), 3614 _overflow_stack(overflow_stack) 3615 { } 3616 virtual void do_oop(oop* p); 3617 virtual void do_oop(narrowOop* p); 3618 3619 void trim_queue(size_t max); 3620 void handle_stack_overflow(HeapWord* lost); 3621 void do_yield_check() { 3622 if (_task->should_yield()) { 3623 _task->yield(); 3624 } 3625 } 3626 }; 3627 3628 // Grey object scanning during work stealing phase -- 3629 // the salient assumption here is that any references 3630 // that are in these stolen objects being scanned must 3631 // already have been initialized (else they would not have 3632 // been published), so we do not need to check for 3633 // uninitialized objects before pushing here. 3634 void Par_ConcMarkingClosure::do_oop(oop obj) { 3635 assert(obj->is_oop_or_null(true), err_msg("Expected an oop or NULL at " PTR_FORMAT, p2i(obj))); 3636 HeapWord* addr = (HeapWord*)obj; 3637 // Check if oop points into the CMS generation 3638 // and is not marked 3639 if (_span.contains(addr) && !_bit_map->isMarked(addr)) { 3640 // a white object ... 3641 // If we manage to "claim" the object, by being the 3642 // first thread to mark it, then we push it on our 3643 // marking stack 3644 if (_bit_map->par_mark(addr)) { // ... now grey 3645 // push on work queue (grey set) 3646 bool simulate_overflow = false; 3647 NOT_PRODUCT( 3648 if (CMSMarkStackOverflowALot && 3649 _collector->simulate_overflow()) { 3650 // simulate a stack overflow 3651 simulate_overflow = true; 3652 } 3653 ) 3654 if (simulate_overflow || 3655 !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) { 3656 // stack overflow 3657 if (PrintCMSStatistics != 0) { 3658 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at " 3659 SIZE_FORMAT, _overflow_stack->capacity()); 3660 } 3661 // We cannot assert that the overflow stack is full because 3662 // it may have been emptied since. 3663 assert(simulate_overflow || 3664 _work_queue->size() == _work_queue->max_elems(), 3665 "Else push should have succeeded"); 3666 handle_stack_overflow(addr); 3667 } 3668 } // Else, some other thread got there first 3669 do_yield_check(); 3670 } 3671 } 3672 3673 void Par_ConcMarkingClosure::do_oop(oop* p) { Par_ConcMarkingClosure::do_oop_work(p); } 3674 void Par_ConcMarkingClosure::do_oop(narrowOop* p) { Par_ConcMarkingClosure::do_oop_work(p); } 3675 3676 void Par_ConcMarkingClosure::trim_queue(size_t max) { 3677 while (_work_queue->size() > max) { 3678 oop new_oop; 3679 if (_work_queue->pop_local(new_oop)) { 3680 assert(new_oop->is_oop(), "Should be an oop"); 3681 assert(_bit_map->isMarked((HeapWord*)new_oop), "Grey object"); 3682 assert(_span.contains((HeapWord*)new_oop), "Not in span"); 3683 new_oop->oop_iterate(this); // do_oop() above 3684 do_yield_check(); 3685 } 3686 } 3687 } 3688 3689 // Upon stack overflow, we discard (part of) the stack, 3690 // remembering the least address amongst those discarded 3691 // in CMSCollector's _restart_address. 3692 void Par_ConcMarkingClosure::handle_stack_overflow(HeapWord* lost) { 3693 // We need to do this under a mutex to prevent other 3694 // workers from interfering with the work done below. 3695 MutexLockerEx ml(_overflow_stack->par_lock(), 3696 Mutex::_no_safepoint_check_flag); 3697 // Remember the least grey address discarded 3698 HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost); 3699 _collector->lower_restart_addr(ra); 3700 _overflow_stack->reset(); // discard stack contents 3701 _overflow_stack->expand(); // expand the stack if possible 3702 } 3703 3704 3705 void CMSConcMarkingTask::do_work_steal(int i) { 3706 OopTaskQueue* work_q = work_queue(i); 3707 oop obj_to_scan; 3708 CMSBitMap* bm = &(_collector->_markBitMap); 3709 CMSMarkStack* ovflw = &(_collector->_markStack); 3710 int* seed = _collector->hash_seed(i); 3711 Par_ConcMarkingClosure cl(_collector, this, work_q, bm, ovflw); 3712 while (true) { 3713 cl.trim_queue(0); 3714 assert(work_q->size() == 0, "Should have been emptied above"); 3715 if (get_work_from_overflow_stack(ovflw, work_q)) { 3716 // Can't assert below because the work obtained from the 3717 // overflow stack may already have been stolen from us. 3718 // assert(work_q->size() > 0, "Work from overflow stack"); 3719 continue; 3720 } else if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) { 3721 assert(obj_to_scan->is_oop(), "Should be an oop"); 3722 assert(bm->isMarked((HeapWord*)obj_to_scan), "Grey object"); 3723 obj_to_scan->oop_iterate(&cl); 3724 } else if (terminator()->offer_termination(&_term_term)) { 3725 assert(work_q->size() == 0, "Impossible!"); 3726 break; 3727 } else if (yielding() || should_yield()) { 3728 yield(); 3729 } 3730 } 3731 } 3732 3733 // This is run by the CMS (coordinator) thread. 3734 void CMSConcMarkingTask::coordinator_yield() { 3735 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 3736 "CMS thread should hold CMS token"); 3737 // First give up the locks, then yield, then re-lock 3738 // We should probably use a constructor/destructor idiom to 3739 // do this unlock/lock or modify the MutexUnlocker class to 3740 // serve our purpose. XXX 3741 assert_lock_strong(_bit_map_lock); 3742 _bit_map_lock->unlock(); 3743 ConcurrentMarkSweepThread::desynchronize(true); 3744 _collector->stopTimer(); 3745 if (PrintCMSStatistics != 0) { 3746 _collector->incrementYields(); 3747 } 3748 3749 // It is possible for whichever thread initiated the yield request 3750 // not to get a chance to wake up and take the bitmap lock between 3751 // this thread releasing it and reacquiring it. So, while the 3752 // should_yield() flag is on, let's sleep for a bit to give the 3753 // other thread a chance to wake up. The limit imposed on the number 3754 // of iterations is defensive, to avoid any unforseen circumstances 3755 // putting us into an infinite loop. Since it's always been this 3756 // (coordinator_yield()) method that was observed to cause the 3757 // problem, we are using a parameter (CMSCoordinatorYieldSleepCount) 3758 // which is by default non-zero. For the other seven methods that 3759 // also perform the yield operation, as are using a different 3760 // parameter (CMSYieldSleepCount) which is by default zero. This way we 3761 // can enable the sleeping for those methods too, if necessary. 3762 // See 6442774. 3763 // 3764 // We really need to reconsider the synchronization between the GC 3765 // thread and the yield-requesting threads in the future and we 3766 // should really use wait/notify, which is the recommended 3767 // way of doing this type of interaction. Additionally, we should 3768 // consolidate the eight methods that do the yield operation and they 3769 // are almost identical into one for better maintainability and 3770 // readability. See 6445193. 3771 // 3772 // Tony 2006.06.29 3773 for (unsigned i = 0; i < CMSCoordinatorYieldSleepCount && 3774 ConcurrentMarkSweepThread::should_yield() && 3775 !CMSCollector::foregroundGCIsActive(); ++i) { 3776 os::sleep(Thread::current(), 1, false); 3777 } 3778 3779 ConcurrentMarkSweepThread::synchronize(true); 3780 _bit_map_lock->lock_without_safepoint_check(); 3781 _collector->startTimer(); 3782 } 3783 3784 bool CMSCollector::do_marking_mt() { 3785 assert(ConcGCThreads > 0 && conc_workers() != NULL, "precondition"); 3786 int num_workers = AdaptiveSizePolicy::calc_active_conc_workers( 3787 conc_workers()->total_workers(), 3788 conc_workers()->active_workers(), 3789 Threads::number_of_non_daemon_threads()); 3790 conc_workers()->set_active_workers(num_workers); 3791 3792 CompactibleFreeListSpace* cms_space = _cmsGen->cmsSpace(); 3793 3794 CMSConcMarkingTask tsk(this, 3795 cms_space, 3796 conc_workers(), 3797 task_queues()); 3798 3799 // Since the actual number of workers we get may be different 3800 // from the number we requested above, do we need to do anything different 3801 // below? In particular, may be we need to subclass the SequantialSubTasksDone 3802 // class?? XXX 3803 cms_space ->initialize_sequential_subtasks_for_marking(num_workers); 3804 3805 // Refs discovery is already non-atomic. 3806 assert(!ref_processor()->discovery_is_atomic(), "Should be non-atomic"); 3807 assert(ref_processor()->discovery_is_mt(), "Discovery should be MT"); 3808 conc_workers()->start_task(&tsk); 3809 while (tsk.yielded()) { 3810 tsk.coordinator_yield(); 3811 conc_workers()->continue_task(&tsk); 3812 } 3813 // If the task was aborted, _restart_addr will be non-NULL 3814 assert(tsk.completed() || _restart_addr != NULL, "Inconsistency"); 3815 while (_restart_addr != NULL) { 3816 // XXX For now we do not make use of ABORTED state and have not 3817 // yet implemented the right abort semantics (even in the original 3818 // single-threaded CMS case). That needs some more investigation 3819 // and is deferred for now; see CR# TBF. 07252005YSR. XXX 3820 assert(!CMSAbortSemantics || tsk.aborted(), "Inconsistency"); 3821 // If _restart_addr is non-NULL, a marking stack overflow 3822 // occurred; we need to do a fresh marking iteration from the 3823 // indicated restart address. 3824 if (_foregroundGCIsActive) { 3825 // We may be running into repeated stack overflows, having 3826 // reached the limit of the stack size, while making very 3827 // slow forward progress. It may be best to bail out and 3828 // let the foreground collector do its job. 3829 // Clear _restart_addr, so that foreground GC 3830 // works from scratch. This avoids the headache of 3831 // a "rescan" which would otherwise be needed because 3832 // of the dirty mod union table & card table. 3833 _restart_addr = NULL; 3834 return false; 3835 } 3836 // Adjust the task to restart from _restart_addr 3837 tsk.reset(_restart_addr); 3838 cms_space ->initialize_sequential_subtasks_for_marking(num_workers, 3839 _restart_addr); 3840 _restart_addr = NULL; 3841 // Get the workers going again 3842 conc_workers()->start_task(&tsk); 3843 while (tsk.yielded()) { 3844 tsk.coordinator_yield(); 3845 conc_workers()->continue_task(&tsk); 3846 } 3847 } 3848 assert(tsk.completed(), "Inconsistency"); 3849 assert(tsk.result() == true, "Inconsistency"); 3850 return true; 3851 } 3852 3853 bool CMSCollector::do_marking_st() { 3854 ResourceMark rm; 3855 HandleMark hm; 3856 3857 // Temporarily make refs discovery single threaded (non-MT) 3858 ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(ref_processor(), false); 3859 MarkFromRootsClosure markFromRootsClosure(this, _span, &_markBitMap, 3860 &_markStack, CMSYield); 3861 // the last argument to iterate indicates whether the iteration 3862 // should be incremental with periodic yields. 3863 _markBitMap.iterate(&markFromRootsClosure); 3864 // If _restart_addr is non-NULL, a marking stack overflow 3865 // occurred; we need to do a fresh iteration from the 3866 // indicated restart address. 3867 while (_restart_addr != NULL) { 3868 if (_foregroundGCIsActive) { 3869 // We may be running into repeated stack overflows, having 3870 // reached the limit of the stack size, while making very 3871 // slow forward progress. It may be best to bail out and 3872 // let the foreground collector do its job. 3873 // Clear _restart_addr, so that foreground GC 3874 // works from scratch. This avoids the headache of 3875 // a "rescan" which would otherwise be needed because 3876 // of the dirty mod union table & card table. 3877 _restart_addr = NULL; 3878 return false; // indicating failure to complete marking 3879 } 3880 // Deal with stack overflow: 3881 // we restart marking from _restart_addr 3882 HeapWord* ra = _restart_addr; 3883 markFromRootsClosure.reset(ra); 3884 _restart_addr = NULL; 3885 _markBitMap.iterate(&markFromRootsClosure, ra, _span.end()); 3886 } 3887 return true; 3888 } 3889 3890 void CMSCollector::preclean() { 3891 check_correct_thread_executing(); 3892 assert(Thread::current()->is_ConcurrentGC_thread(), "Wrong thread"); 3893 verify_work_stacks_empty(); 3894 verify_overflow_empty(); 3895 _abort_preclean = false; 3896 if (CMSPrecleaningEnabled) { 3897 if (!CMSEdenChunksRecordAlways) { 3898 _eden_chunk_index = 0; 3899 } 3900 size_t used = get_eden_used(); 3901 size_t capacity = get_eden_capacity(); 3902 // Don't start sampling unless we will get sufficiently 3903 // many samples. 3904 if (used < (capacity/(CMSScheduleRemarkSamplingRatio * 100) 3905 * CMSScheduleRemarkEdenPenetration)) { 3906 _start_sampling = true; 3907 } else { 3908 _start_sampling = false; 3909 } 3910 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 3911 CMSPhaseAccounting pa(this, "preclean", _gc_tracer_cm->gc_id(), !PrintGCDetails); 3912 preclean_work(CMSPrecleanRefLists1, CMSPrecleanSurvivors1); 3913 } 3914 CMSTokenSync x(true); // is cms thread 3915 if (CMSPrecleaningEnabled) { 3916 sample_eden(); 3917 _collectorState = AbortablePreclean; 3918 } else { 3919 _collectorState = FinalMarking; 3920 } 3921 verify_work_stacks_empty(); 3922 verify_overflow_empty(); 3923 } 3924 3925 // Try and schedule the remark such that young gen 3926 // occupancy is CMSScheduleRemarkEdenPenetration %. 3927 void CMSCollector::abortable_preclean() { 3928 check_correct_thread_executing(); 3929 assert(CMSPrecleaningEnabled, "Inconsistent control state"); 3930 assert(_collectorState == AbortablePreclean, "Inconsistent control state"); 3931 3932 // If Eden's current occupancy is below this threshold, 3933 // immediately schedule the remark; else preclean 3934 // past the next scavenge in an effort to 3935 // schedule the pause as described above. By choosing 3936 // CMSScheduleRemarkEdenSizeThreshold >= max eden size 3937 // we will never do an actual abortable preclean cycle. 3938 if (get_eden_used() > CMSScheduleRemarkEdenSizeThreshold) { 3939 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 3940 CMSPhaseAccounting pa(this, "abortable-preclean", _gc_tracer_cm->gc_id(), !PrintGCDetails); 3941 // We need more smarts in the abortable preclean 3942 // loop below to deal with cases where allocation 3943 // in young gen is very very slow, and our precleaning 3944 // is running a losing race against a horde of 3945 // mutators intent on flooding us with CMS updates 3946 // (dirty cards). 3947 // One, admittedly dumb, strategy is to give up 3948 // after a certain number of abortable precleaning loops 3949 // or after a certain maximum time. We want to make 3950 // this smarter in the next iteration. 3951 // XXX FIX ME!!! YSR 3952 size_t loops = 0, workdone = 0, cumworkdone = 0, waited = 0; 3953 while (!(should_abort_preclean() || 3954 ConcurrentMarkSweepThread::should_terminate())) { 3955 workdone = preclean_work(CMSPrecleanRefLists2, CMSPrecleanSurvivors2); 3956 cumworkdone += workdone; 3957 loops++; 3958 // Voluntarily terminate abortable preclean phase if we have 3959 // been at it for too long. 3960 if ((CMSMaxAbortablePrecleanLoops != 0) && 3961 loops >= CMSMaxAbortablePrecleanLoops) { 3962 if (PrintGCDetails) { 3963 gclog_or_tty->print(" CMS: abort preclean due to loops "); 3964 } 3965 break; 3966 } 3967 if (pa.wallclock_millis() > CMSMaxAbortablePrecleanTime) { 3968 if (PrintGCDetails) { 3969 gclog_or_tty->print(" CMS: abort preclean due to time "); 3970 } 3971 break; 3972 } 3973 // If we are doing little work each iteration, we should 3974 // take a short break. 3975 if (workdone < CMSAbortablePrecleanMinWorkPerIteration) { 3976 // Sleep for some time, waiting for work to accumulate 3977 stopTimer(); 3978 cmsThread()->wait_on_cms_lock(CMSAbortablePrecleanWaitMillis); 3979 startTimer(); 3980 waited++; 3981 } 3982 } 3983 if (PrintCMSStatistics > 0) { 3984 gclog_or_tty->print(" [" SIZE_FORMAT " iterations, " SIZE_FORMAT " waits, " SIZE_FORMAT " cards)] ", 3985 loops, waited, cumworkdone); 3986 } 3987 } 3988 CMSTokenSync x(true); // is cms thread 3989 if (_collectorState != Idling) { 3990 assert(_collectorState == AbortablePreclean, 3991 "Spontaneous state transition?"); 3992 _collectorState = FinalMarking; 3993 } // Else, a foreground collection completed this CMS cycle. 3994 return; 3995 } 3996 3997 // Respond to an Eden sampling opportunity 3998 void CMSCollector::sample_eden() { 3999 // Make sure a young gc cannot sneak in between our 4000 // reading and recording of a sample. 4001 assert(Thread::current()->is_ConcurrentGC_thread(), 4002 "Only the cms thread may collect Eden samples"); 4003 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 4004 "Should collect samples while holding CMS token"); 4005 if (!_start_sampling) { 4006 return; 4007 } 4008 // When CMSEdenChunksRecordAlways is true, the eden chunk array 4009 // is populated by the young generation. 4010 if (_eden_chunk_array != NULL && !CMSEdenChunksRecordAlways) { 4011 if (_eden_chunk_index < _eden_chunk_capacity) { 4012 _eden_chunk_array[_eden_chunk_index] = *_top_addr; // take sample 4013 assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr, 4014 "Unexpected state of Eden"); 4015 // We'd like to check that what we just sampled is an oop-start address; 4016 // however, we cannot do that here since the object may not yet have been 4017 // initialized. So we'll instead do the check when we _use_ this sample 4018 // later. 4019 if (_eden_chunk_index == 0 || 4020 (pointer_delta(_eden_chunk_array[_eden_chunk_index], 4021 _eden_chunk_array[_eden_chunk_index-1]) 4022 >= CMSSamplingGrain)) { 4023 _eden_chunk_index++; // commit sample 4024 } 4025 } 4026 } 4027 if ((_collectorState == AbortablePreclean) && !_abort_preclean) { 4028 size_t used = get_eden_used(); 4029 size_t capacity = get_eden_capacity(); 4030 assert(used <= capacity, "Unexpected state of Eden"); 4031 if (used > (capacity/100 * CMSScheduleRemarkEdenPenetration)) { 4032 _abort_preclean = true; 4033 } 4034 } 4035 } 4036 4037 4038 size_t CMSCollector::preclean_work(bool clean_refs, bool clean_survivor) { 4039 assert(_collectorState == Precleaning || 4040 _collectorState == AbortablePreclean, "incorrect state"); 4041 ResourceMark rm; 4042 HandleMark hm; 4043 4044 // Precleaning is currently not MT but the reference processor 4045 // may be set for MT. Disable it temporarily here. 4046 ReferenceProcessor* rp = ref_processor(); 4047 ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(rp, false); 4048 4049 // Do one pass of scrubbing the discovered reference lists 4050 // to remove any reference objects with strongly-reachable 4051 // referents. 4052 if (clean_refs) { 4053 CMSPrecleanRefsYieldClosure yield_cl(this); 4054 assert(rp->span().equals(_span), "Spans should be equal"); 4055 CMSKeepAliveClosure keep_alive(this, _span, &_markBitMap, 4056 &_markStack, true /* preclean */); 4057 CMSDrainMarkingStackClosure complete_trace(this, 4058 _span, &_markBitMap, &_markStack, 4059 &keep_alive, true /* preclean */); 4060 4061 // We don't want this step to interfere with a young 4062 // collection because we don't want to take CPU 4063 // or memory bandwidth away from the young GC threads 4064 // (which may be as many as there are CPUs). 4065 // Note that we don't need to protect ourselves from 4066 // interference with mutators because they can't 4067 // manipulate the discovered reference lists nor affect 4068 // the computed reachability of the referents, the 4069 // only properties manipulated by the precleaning 4070 // of these reference lists. 4071 stopTimer(); 4072 CMSTokenSyncWithLocks x(true /* is cms thread */, 4073 bitMapLock()); 4074 startTimer(); 4075 sample_eden(); 4076 4077 // The following will yield to allow foreground 4078 // collection to proceed promptly. XXX YSR: 4079 // The code in this method may need further 4080 // tweaking for better performance and some restructuring 4081 // for cleaner interfaces. 4082 GCTimer *gc_timer = NULL; // Currently not tracing concurrent phases 4083 rp->preclean_discovered_references( 4084 rp->is_alive_non_header(), &keep_alive, &complete_trace, &yield_cl, 4085 gc_timer, _gc_tracer_cm->gc_id()); 4086 } 4087 4088 if (clean_survivor) { // preclean the active survivor space(s) 4089 DefNewGeneration* dng = _young_gen->as_DefNewGeneration(); 4090 PushAndMarkClosure pam_cl(this, _span, ref_processor(), 4091 &_markBitMap, &_modUnionTable, 4092 &_markStack, true /* precleaning phase */); 4093 stopTimer(); 4094 CMSTokenSyncWithLocks ts(true /* is cms thread */, 4095 bitMapLock()); 4096 startTimer(); 4097 unsigned int before_count = 4098 GenCollectedHeap::heap()->total_collections(); 4099 SurvivorSpacePrecleanClosure 4100 sss_cl(this, _span, &_markBitMap, &_markStack, 4101 &pam_cl, before_count, CMSYield); 4102 dng->from()->object_iterate_careful(&sss_cl); 4103 dng->to()->object_iterate_careful(&sss_cl); 4104 } 4105 MarkRefsIntoAndScanClosure 4106 mrias_cl(_span, ref_processor(), &_markBitMap, &_modUnionTable, 4107 &_markStack, this, CMSYield, 4108 true /* precleaning phase */); 4109 // CAUTION: The following closure has persistent state that may need to 4110 // be reset upon a decrease in the sequence of addresses it 4111 // processes. 4112 ScanMarkedObjectsAgainCarefullyClosure 4113 smoac_cl(this, _span, 4114 &_markBitMap, &_markStack, &mrias_cl, CMSYield); 4115 4116 // Preclean dirty cards in ModUnionTable and CardTable using 4117 // appropriate convergence criterion; 4118 // repeat CMSPrecleanIter times unless we find that 4119 // we are losing. 4120 assert(CMSPrecleanIter < 10, "CMSPrecleanIter is too large"); 4121 assert(CMSPrecleanNumerator < CMSPrecleanDenominator, 4122 "Bad convergence multiplier"); 4123 assert(CMSPrecleanThreshold >= 100, 4124 "Unreasonably low CMSPrecleanThreshold"); 4125 4126 size_t numIter, cumNumCards, lastNumCards, curNumCards; 4127 for (numIter = 0, cumNumCards = lastNumCards = curNumCards = 0; 4128 numIter < CMSPrecleanIter; 4129 numIter++, lastNumCards = curNumCards, cumNumCards += curNumCards) { 4130 curNumCards = preclean_mod_union_table(_cmsGen, &smoac_cl); 4131 if (Verbose && PrintGCDetails) { 4132 gclog_or_tty->print(" (modUnionTable: " SIZE_FORMAT " cards)", curNumCards); 4133 } 4134 // Either there are very few dirty cards, so re-mark 4135 // pause will be small anyway, or our pre-cleaning isn't 4136 // that much faster than the rate at which cards are being 4137 // dirtied, so we might as well stop and re-mark since 4138 // precleaning won't improve our re-mark time by much. 4139 if (curNumCards <= CMSPrecleanThreshold || 4140 (numIter > 0 && 4141 (curNumCards * CMSPrecleanDenominator > 4142 lastNumCards * CMSPrecleanNumerator))) { 4143 numIter++; 4144 cumNumCards += curNumCards; 4145 break; 4146 } 4147 } 4148 4149 preclean_klasses(&mrias_cl, _cmsGen->freelistLock()); 4150 4151 curNumCards = preclean_card_table(_cmsGen, &smoac_cl); 4152 cumNumCards += curNumCards; 4153 if (PrintGCDetails && PrintCMSStatistics != 0) { 4154 gclog_or_tty->print_cr(" (cardTable: " SIZE_FORMAT " cards, re-scanned " SIZE_FORMAT " cards, " SIZE_FORMAT " iterations)", 4155 curNumCards, cumNumCards, numIter); 4156 } 4157 return cumNumCards; // as a measure of useful work done 4158 } 4159 4160 // PRECLEANING NOTES: 4161 // Precleaning involves: 4162 // . reading the bits of the modUnionTable and clearing the set bits. 4163 // . For the cards corresponding to the set bits, we scan the 4164 // objects on those cards. This means we need the free_list_lock 4165 // so that we can safely iterate over the CMS space when scanning 4166 // for oops. 4167 // . When we scan the objects, we'll be both reading and setting 4168 // marks in the marking bit map, so we'll need the marking bit map. 4169 // . For protecting _collector_state transitions, we take the CGC_lock. 4170 // Note that any races in the reading of of card table entries by the 4171 // CMS thread on the one hand and the clearing of those entries by the 4172 // VM thread or the setting of those entries by the mutator threads on the 4173 // other are quite benign. However, for efficiency it makes sense to keep 4174 // the VM thread from racing with the CMS thread while the latter is 4175 // dirty card info to the modUnionTable. We therefore also use the 4176 // CGC_lock to protect the reading of the card table and the mod union 4177 // table by the CM thread. 4178 // . We run concurrently with mutator updates, so scanning 4179 // needs to be done carefully -- we should not try to scan 4180 // potentially uninitialized objects. 4181 // 4182 // Locking strategy: While holding the CGC_lock, we scan over and 4183 // reset a maximal dirty range of the mod union / card tables, then lock 4184 // the free_list_lock and bitmap lock to do a full marking, then 4185 // release these locks; and repeat the cycle. This allows for a 4186 // certain amount of fairness in the sharing of these locks between 4187 // the CMS collector on the one hand, and the VM thread and the 4188 // mutators on the other. 4189 4190 // NOTE: preclean_mod_union_table() and preclean_card_table() 4191 // further below are largely identical; if you need to modify 4192 // one of these methods, please check the other method too. 4193 4194 size_t CMSCollector::preclean_mod_union_table( 4195 ConcurrentMarkSweepGeneration* gen, 4196 ScanMarkedObjectsAgainCarefullyClosure* cl) { 4197 verify_work_stacks_empty(); 4198 verify_overflow_empty(); 4199 4200 // strategy: starting with the first card, accumulate contiguous 4201 // ranges of dirty cards; clear these cards, then scan the region 4202 // covered by these cards. 4203 4204 // Since all of the MUT is committed ahead, we can just use 4205 // that, in case the generations expand while we are precleaning. 4206 // It might also be fine to just use the committed part of the 4207 // generation, but we might potentially miss cards when the 4208 // generation is rapidly expanding while we are in the midst 4209 // of precleaning. 4210 HeapWord* startAddr = gen->reserved().start(); 4211 HeapWord* endAddr = gen->reserved().end(); 4212 4213 cl->setFreelistLock(gen->freelistLock()); // needed for yielding 4214 4215 size_t numDirtyCards, cumNumDirtyCards; 4216 HeapWord *nextAddr, *lastAddr; 4217 for (cumNumDirtyCards = numDirtyCards = 0, 4218 nextAddr = lastAddr = startAddr; 4219 nextAddr < endAddr; 4220 nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) { 4221 4222 ResourceMark rm; 4223 HandleMark hm; 4224 4225 MemRegion dirtyRegion; 4226 { 4227 stopTimer(); 4228 // Potential yield point 4229 CMSTokenSync ts(true); 4230 startTimer(); 4231 sample_eden(); 4232 // Get dirty region starting at nextOffset (inclusive), 4233 // simultaneously clearing it. 4234 dirtyRegion = 4235 _modUnionTable.getAndClearMarkedRegion(nextAddr, endAddr); 4236 assert(dirtyRegion.start() >= nextAddr, 4237 "returned region inconsistent?"); 4238 } 4239 // Remember where the next search should begin. 4240 // The returned region (if non-empty) is a right open interval, 4241 // so lastOffset is obtained from the right end of that 4242 // interval. 4243 lastAddr = dirtyRegion.end(); 4244 // Should do something more transparent and less hacky XXX 4245 numDirtyCards = 4246 _modUnionTable.heapWordDiffToOffsetDiff(dirtyRegion.word_size()); 4247 4248 // We'll scan the cards in the dirty region (with periodic 4249 // yields for foreground GC as needed). 4250 if (!dirtyRegion.is_empty()) { 4251 assert(numDirtyCards > 0, "consistency check"); 4252 HeapWord* stop_point = NULL; 4253 stopTimer(); 4254 // Potential yield point 4255 CMSTokenSyncWithLocks ts(true, gen->freelistLock(), 4256 bitMapLock()); 4257 startTimer(); 4258 { 4259 verify_work_stacks_empty(); 4260 verify_overflow_empty(); 4261 sample_eden(); 4262 stop_point = 4263 gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl); 4264 } 4265 if (stop_point != NULL) { 4266 // The careful iteration stopped early either because it found an 4267 // uninitialized object, or because we were in the midst of an 4268 // "abortable preclean", which should now be aborted. Redirty 4269 // the bits corresponding to the partially-scanned or unscanned 4270 // cards. We'll either restart at the next block boundary or 4271 // abort the preclean. 4272 assert((_collectorState == AbortablePreclean && should_abort_preclean()), 4273 "Should only be AbortablePreclean."); 4274 _modUnionTable.mark_range(MemRegion(stop_point, dirtyRegion.end())); 4275 if (should_abort_preclean()) { 4276 break; // out of preclean loop 4277 } else { 4278 // Compute the next address at which preclean should pick up; 4279 // might need bitMapLock in order to read P-bits. 4280 lastAddr = next_card_start_after_block(stop_point); 4281 } 4282 } 4283 } else { 4284 assert(lastAddr == endAddr, "consistency check"); 4285 assert(numDirtyCards == 0, "consistency check"); 4286 break; 4287 } 4288 } 4289 verify_work_stacks_empty(); 4290 verify_overflow_empty(); 4291 return cumNumDirtyCards; 4292 } 4293 4294 // NOTE: preclean_mod_union_table() above and preclean_card_table() 4295 // below are largely identical; if you need to modify 4296 // one of these methods, please check the other method too. 4297 4298 size_t CMSCollector::preclean_card_table(ConcurrentMarkSweepGeneration* gen, 4299 ScanMarkedObjectsAgainCarefullyClosure* cl) { 4300 // strategy: it's similar to precleamModUnionTable above, in that 4301 // we accumulate contiguous ranges of dirty cards, mark these cards 4302 // precleaned, then scan the region covered by these cards. 4303 HeapWord* endAddr = (HeapWord*)(gen->_virtual_space.high()); 4304 HeapWord* startAddr = (HeapWord*)(gen->_virtual_space.low()); 4305 4306 cl->setFreelistLock(gen->freelistLock()); // needed for yielding 4307 4308 size_t numDirtyCards, cumNumDirtyCards; 4309 HeapWord *lastAddr, *nextAddr; 4310 4311 for (cumNumDirtyCards = numDirtyCards = 0, 4312 nextAddr = lastAddr = startAddr; 4313 nextAddr < endAddr; 4314 nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) { 4315 4316 ResourceMark rm; 4317 HandleMark hm; 4318 4319 MemRegion dirtyRegion; 4320 { 4321 // See comments in "Precleaning notes" above on why we 4322 // do this locking. XXX Could the locking overheads be 4323 // too high when dirty cards are sparse? [I don't think so.] 4324 stopTimer(); 4325 CMSTokenSync x(true); // is cms thread 4326 startTimer(); 4327 sample_eden(); 4328 // Get and clear dirty region from card table 4329 dirtyRegion = _ct->ct_bs()->dirty_card_range_after_reset( 4330 MemRegion(nextAddr, endAddr), 4331 true, 4332 CardTableModRefBS::precleaned_card_val()); 4333 4334 assert(dirtyRegion.start() >= nextAddr, 4335 "returned region inconsistent?"); 4336 } 4337 lastAddr = dirtyRegion.end(); 4338 numDirtyCards = 4339 dirtyRegion.word_size()/CardTableModRefBS::card_size_in_words; 4340 4341 if (!dirtyRegion.is_empty()) { 4342 stopTimer(); 4343 CMSTokenSyncWithLocks ts(true, gen->freelistLock(), bitMapLock()); 4344 startTimer(); 4345 sample_eden(); 4346 verify_work_stacks_empty(); 4347 verify_overflow_empty(); 4348 HeapWord* stop_point = 4349 gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl); 4350 if (stop_point != NULL) { 4351 assert((_collectorState == AbortablePreclean && should_abort_preclean()), 4352 "Should only be AbortablePreclean."); 4353 _ct->ct_bs()->invalidate(MemRegion(stop_point, dirtyRegion.end())); 4354 if (should_abort_preclean()) { 4355 break; // out of preclean loop 4356 } else { 4357 // Compute the next address at which preclean should pick up. 4358 lastAddr = next_card_start_after_block(stop_point); 4359 } 4360 } 4361 } else { 4362 break; 4363 } 4364 } 4365 verify_work_stacks_empty(); 4366 verify_overflow_empty(); 4367 return cumNumDirtyCards; 4368 } 4369 4370 class PrecleanKlassClosure : public KlassClosure { 4371 KlassToOopClosure _cm_klass_closure; 4372 public: 4373 PrecleanKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {} 4374 void do_klass(Klass* k) { 4375 if (k->has_accumulated_modified_oops()) { 4376 k->clear_accumulated_modified_oops(); 4377 4378 _cm_klass_closure.do_klass(k); 4379 } 4380 } 4381 }; 4382 4383 // The freelist lock is needed to prevent asserts, is it really needed? 4384 void CMSCollector::preclean_klasses(MarkRefsIntoAndScanClosure* cl, Mutex* freelistLock) { 4385 4386 cl->set_freelistLock(freelistLock); 4387 4388 CMSTokenSyncWithLocks ts(true, freelistLock, bitMapLock()); 4389 4390 // SSS: Add equivalent to ScanMarkedObjectsAgainCarefullyClosure::do_yield_check and should_abort_preclean? 4391 // SSS: We should probably check if precleaning should be aborted, at suitable intervals? 4392 PrecleanKlassClosure preclean_klass_closure(cl); 4393 ClassLoaderDataGraph::classes_do(&preclean_klass_closure); 4394 4395 verify_work_stacks_empty(); 4396 verify_overflow_empty(); 4397 } 4398 4399 void CMSCollector::checkpointRootsFinal() { 4400 assert(_collectorState == FinalMarking, "incorrect state transition?"); 4401 check_correct_thread_executing(); 4402 // world is stopped at this checkpoint 4403 assert(SafepointSynchronize::is_at_safepoint(), 4404 "world should be stopped"); 4405 TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause()); 4406 4407 verify_work_stacks_empty(); 4408 verify_overflow_empty(); 4409 4410 SpecializationStats::clear(); 4411 if (PrintGCDetails) { 4412 gclog_or_tty->print("[YG occupancy: "SIZE_FORMAT" K ("SIZE_FORMAT" K)]", 4413 _young_gen->used() / K, 4414 _young_gen->capacity() / K); 4415 } 4416 { 4417 if (CMSScavengeBeforeRemark) { 4418 GenCollectedHeap* gch = GenCollectedHeap::heap(); 4419 // Temporarily set flag to false, GCH->do_collection will 4420 // expect it to be false and set to true 4421 FlagSetting fl(gch->_is_gc_active, false); 4422 NOT_PRODUCT(GCTraceTime t("Scavenge-Before-Remark", 4423 PrintGCDetails && Verbose, true, _gc_timer_cm, _gc_tracer_cm->gc_id());) 4424 int level = _cmsGen->level() - 1; 4425 if (level >= 0) { 4426 gch->do_collection(true, // full (i.e. force, see below) 4427 false, // !clear_all_soft_refs 4428 0, // size 4429 false, // is_tlab 4430 level // max_level 4431 ); 4432 } 4433 } 4434 FreelistLocker x(this); 4435 MutexLockerEx y(bitMapLock(), 4436 Mutex::_no_safepoint_check_flag); 4437 checkpointRootsFinalWork(); 4438 } 4439 verify_work_stacks_empty(); 4440 verify_overflow_empty(); 4441 SpecializationStats::print(); 4442 } 4443 4444 void CMSCollector::checkpointRootsFinalWork() { 4445 NOT_PRODUCT(GCTraceTime tr("checkpointRootsFinalWork", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());) 4446 4447 assert(haveFreelistLocks(), "must have free list locks"); 4448 assert_lock_strong(bitMapLock()); 4449 4450 ResourceMark rm; 4451 HandleMark hm; 4452 4453 GenCollectedHeap* gch = GenCollectedHeap::heap(); 4454 4455 if (should_unload_classes()) { 4456 CodeCache::gc_prologue(); 4457 } 4458 assert(haveFreelistLocks(), "must have free list locks"); 4459 assert_lock_strong(bitMapLock()); 4460 4461 // We might assume that we need not fill TLAB's when 4462 // CMSScavengeBeforeRemark is set, because we may have just done 4463 // a scavenge which would have filled all TLAB's -- and besides 4464 // Eden would be empty. This however may not always be the case -- 4465 // for instance although we asked for a scavenge, it may not have 4466 // happened because of a JNI critical section. We probably need 4467 // a policy for deciding whether we can in that case wait until 4468 // the critical section releases and then do the remark following 4469 // the scavenge, and skip it here. In the absence of that policy, 4470 // or of an indication of whether the scavenge did indeed occur, 4471 // we cannot rely on TLAB's having been filled and must do 4472 // so here just in case a scavenge did not happen. 4473 gch->ensure_parsability(false); // fill TLAB's, but no need to retire them 4474 // Update the saved marks which may affect the root scans. 4475 gch->save_marks(); 4476 4477 if (CMSPrintEdenSurvivorChunks) { 4478 print_eden_and_survivor_chunk_arrays(); 4479 } 4480 4481 { 4482 COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;) 4483 4484 // Note on the role of the mod union table: 4485 // Since the marker in "markFromRoots" marks concurrently with 4486 // mutators, it is possible for some reachable objects not to have been 4487 // scanned. For instance, an only reference to an object A was 4488 // placed in object B after the marker scanned B. Unless B is rescanned, 4489 // A would be collected. Such updates to references in marked objects 4490 // are detected via the mod union table which is the set of all cards 4491 // dirtied since the first checkpoint in this GC cycle and prior to 4492 // the most recent young generation GC, minus those cleaned up by the 4493 // concurrent precleaning. 4494 if (CMSParallelRemarkEnabled && CollectedHeap::use_parallel_gc_threads()) { 4495 GCTraceTime t("Rescan (parallel) ", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 4496 do_remark_parallel(); 4497 } else { 4498 GCTraceTime t("Rescan (non-parallel) ", PrintGCDetails, false, 4499 _gc_timer_cm, _gc_tracer_cm->gc_id()); 4500 do_remark_non_parallel(); 4501 } 4502 } 4503 verify_work_stacks_empty(); 4504 verify_overflow_empty(); 4505 4506 { 4507 NOT_PRODUCT(GCTraceTime ts("refProcessingWork", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());) 4508 refProcessingWork(); 4509 } 4510 verify_work_stacks_empty(); 4511 verify_overflow_empty(); 4512 4513 if (should_unload_classes()) { 4514 CodeCache::gc_epilogue(); 4515 } 4516 JvmtiExport::gc_epilogue(); 4517 4518 // If we encountered any (marking stack / work queue) overflow 4519 // events during the current CMS cycle, take appropriate 4520 // remedial measures, where possible, so as to try and avoid 4521 // recurrence of that condition. 4522 assert(_markStack.isEmpty(), "No grey objects"); 4523 size_t ser_ovflw = _ser_pmc_remark_ovflw + _ser_pmc_preclean_ovflw + 4524 _ser_kac_ovflw + _ser_kac_preclean_ovflw; 4525 if (ser_ovflw > 0) { 4526 if (PrintCMSStatistics != 0) { 4527 gclog_or_tty->print_cr("Marking stack overflow (benign) " 4528 "(pmc_pc="SIZE_FORMAT", pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT 4529 ", kac_preclean="SIZE_FORMAT")", 4530 _ser_pmc_preclean_ovflw, _ser_pmc_remark_ovflw, 4531 _ser_kac_ovflw, _ser_kac_preclean_ovflw); 4532 } 4533 _markStack.expand(); 4534 _ser_pmc_remark_ovflw = 0; 4535 _ser_pmc_preclean_ovflw = 0; 4536 _ser_kac_preclean_ovflw = 0; 4537 _ser_kac_ovflw = 0; 4538 } 4539 if (_par_pmc_remark_ovflw > 0 || _par_kac_ovflw > 0) { 4540 if (PrintCMSStatistics != 0) { 4541 gclog_or_tty->print_cr("Work queue overflow (benign) " 4542 "(pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT")", 4543 _par_pmc_remark_ovflw, _par_kac_ovflw); 4544 } 4545 _par_pmc_remark_ovflw = 0; 4546 _par_kac_ovflw = 0; 4547 } 4548 if (PrintCMSStatistics != 0) { 4549 if (_markStack._hit_limit > 0) { 4550 gclog_or_tty->print_cr(" (benign) Hit max stack size limit ("SIZE_FORMAT")", 4551 _markStack._hit_limit); 4552 } 4553 if (_markStack._failed_double > 0) { 4554 gclog_or_tty->print_cr(" (benign) Failed stack doubling ("SIZE_FORMAT")," 4555 " current capacity "SIZE_FORMAT, 4556 _markStack._failed_double, 4557 _markStack.capacity()); 4558 } 4559 } 4560 _markStack._hit_limit = 0; 4561 _markStack._failed_double = 0; 4562 4563 if ((VerifyAfterGC || VerifyDuringGC) && 4564 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) { 4565 verify_after_remark(); 4566 } 4567 4568 _gc_tracer_cm->report_object_count_after_gc(&_is_alive_closure); 4569 4570 // Change under the freelistLocks. 4571 _collectorState = Sweeping; 4572 // Call isAllClear() under bitMapLock 4573 assert(_modUnionTable.isAllClear(), 4574 "Should be clear by end of the final marking"); 4575 assert(_ct->klass_rem_set()->mod_union_is_clear(), 4576 "Should be clear by end of the final marking"); 4577 } 4578 4579 void CMSParInitialMarkTask::work(uint worker_id) { 4580 elapsedTimer _timer; 4581 ResourceMark rm; 4582 HandleMark hm; 4583 4584 // ---------- scan from roots -------------- 4585 _timer.start(); 4586 GenCollectedHeap* gch = GenCollectedHeap::heap(); 4587 Par_MarkRefsIntoClosure par_mri_cl(_collector->_span, &(_collector->_markBitMap)); 4588 4589 // ---------- young gen roots -------------- 4590 { 4591 work_on_young_gen_roots(worker_id, &par_mri_cl); 4592 _timer.stop(); 4593 if (PrintCMSStatistics != 0) { 4594 gclog_or_tty->print_cr( 4595 "Finished young gen initial mark scan work in %dth thread: %3.3f sec", 4596 worker_id, _timer.seconds()); 4597 } 4598 } 4599 4600 // ---------- remaining roots -------------- 4601 _timer.reset(); 4602 _timer.start(); 4603 4604 CLDToOopClosure cld_closure(&par_mri_cl, true); 4605 4606 gch->gen_process_roots(_collector->_cmsGen->level(), 4607 false, // yg was scanned above 4608 false, // this is parallel code 4609 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()), 4610 _collector->should_unload_classes(), 4611 &par_mri_cl, 4612 NULL, 4613 &cld_closure); 4614 assert(_collector->should_unload_classes() 4615 || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_AllCodeCache), 4616 "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops"); 4617 _timer.stop(); 4618 if (PrintCMSStatistics != 0) { 4619 gclog_or_tty->print_cr( 4620 "Finished remaining root initial mark scan work in %dth thread: %3.3f sec", 4621 worker_id, _timer.seconds()); 4622 } 4623 } 4624 4625 // Parallel remark task 4626 class CMSParRemarkTask: public CMSParMarkTask { 4627 CompactibleFreeListSpace* _cms_space; 4628 4629 // The per-thread work queues, available here for stealing. 4630 OopTaskQueueSet* _task_queues; 4631 ParallelTaskTerminator _term; 4632 4633 public: 4634 // A value of 0 passed to n_workers will cause the number of 4635 // workers to be taken from the active workers in the work gang. 4636 CMSParRemarkTask(CMSCollector* collector, 4637 CompactibleFreeListSpace* cms_space, 4638 int n_workers, FlexibleWorkGang* workers, 4639 OopTaskQueueSet* task_queues): 4640 CMSParMarkTask("Rescan roots and grey objects in parallel", 4641 collector, n_workers), 4642 _cms_space(cms_space), 4643 _task_queues(task_queues), 4644 _term(n_workers, task_queues) { } 4645 4646 OopTaskQueueSet* task_queues() { return _task_queues; } 4647 4648 OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); } 4649 4650 ParallelTaskTerminator* terminator() { return &_term; } 4651 int n_workers() { return _n_workers; } 4652 4653 void work(uint worker_id); 4654 4655 private: 4656 // ... of dirty cards in old space 4657 void do_dirty_card_rescan_tasks(CompactibleFreeListSpace* sp, int i, 4658 Par_MarkRefsIntoAndScanClosure* cl); 4659 4660 // ... work stealing for the above 4661 void do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl, int* seed); 4662 }; 4663 4664 class RemarkKlassClosure : public KlassClosure { 4665 KlassToOopClosure _cm_klass_closure; 4666 public: 4667 RemarkKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {} 4668 void do_klass(Klass* k) { 4669 // Check if we have modified any oops in the Klass during the concurrent marking. 4670 if (k->has_accumulated_modified_oops()) { 4671 k->clear_accumulated_modified_oops(); 4672 4673 // We could have transfered the current modified marks to the accumulated marks, 4674 // like we do with the Card Table to Mod Union Table. But it's not really necessary. 4675 } else if (k->has_modified_oops()) { 4676 // Don't clear anything, this info is needed by the next young collection. 4677 } else { 4678 // No modified oops in the Klass. 4679 return; 4680 } 4681 4682 // The klass has modified fields, need to scan the klass. 4683 _cm_klass_closure.do_klass(k); 4684 } 4685 }; 4686 4687 void CMSParMarkTask::work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl) { 4688 DefNewGeneration* dng = _collector->_young_gen->as_DefNewGeneration(); 4689 ContiguousSpace* eden_space = dng->eden(); 4690 ContiguousSpace* from_space = dng->from(); 4691 ContiguousSpace* to_space = dng->to(); 4692 4693 HeapWord** eca = _collector->_eden_chunk_array; 4694 size_t ect = _collector->_eden_chunk_index; 4695 HeapWord** sca = _collector->_survivor_chunk_array; 4696 size_t sct = _collector->_survivor_chunk_index; 4697 4698 assert(ect <= _collector->_eden_chunk_capacity, "out of bounds"); 4699 assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds"); 4700 4701 do_young_space_rescan(worker_id, cl, to_space, NULL, 0); 4702 do_young_space_rescan(worker_id, cl, from_space, sca, sct); 4703 do_young_space_rescan(worker_id, cl, eden_space, eca, ect); 4704 } 4705 4706 // work_queue(i) is passed to the closure 4707 // Par_MarkRefsIntoAndScanClosure. The "i" parameter 4708 // also is passed to do_dirty_card_rescan_tasks() and to 4709 // do_work_steal() to select the i-th task_queue. 4710 4711 void CMSParRemarkTask::work(uint worker_id) { 4712 elapsedTimer _timer; 4713 ResourceMark rm; 4714 HandleMark hm; 4715 4716 // ---------- rescan from roots -------------- 4717 _timer.start(); 4718 GenCollectedHeap* gch = GenCollectedHeap::heap(); 4719 Par_MarkRefsIntoAndScanClosure par_mrias_cl(_collector, 4720 _collector->_span, _collector->ref_processor(), 4721 &(_collector->_markBitMap), 4722 work_queue(worker_id)); 4723 4724 // Rescan young gen roots first since these are likely 4725 // coarsely partitioned and may, on that account, constitute 4726 // the critical path; thus, it's best to start off that 4727 // work first. 4728 // ---------- young gen roots -------------- 4729 { 4730 work_on_young_gen_roots(worker_id, &par_mrias_cl); 4731 _timer.stop(); 4732 if (PrintCMSStatistics != 0) { 4733 gclog_or_tty->print_cr( 4734 "Finished young gen rescan work in %dth thread: %3.3f sec", 4735 worker_id, _timer.seconds()); 4736 } 4737 } 4738 4739 // ---------- remaining roots -------------- 4740 _timer.reset(); 4741 _timer.start(); 4742 gch->gen_process_roots(_collector->_cmsGen->level(), 4743 false, // yg was scanned above 4744 false, // this is parallel code 4745 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()), 4746 _collector->should_unload_classes(), 4747 &par_mrias_cl, 4748 NULL, 4749 NULL); // The dirty klasses will be handled below 4750 4751 assert(_collector->should_unload_classes() 4752 || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_AllCodeCache), 4753 "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops"); 4754 _timer.stop(); 4755 if (PrintCMSStatistics != 0) { 4756 gclog_or_tty->print_cr( 4757 "Finished remaining root rescan work in %dth thread: %3.3f sec", 4758 worker_id, _timer.seconds()); 4759 } 4760 4761 // ---------- unhandled CLD scanning ---------- 4762 if (worker_id == 0) { // Single threaded at the moment. 4763 _timer.reset(); 4764 _timer.start(); 4765 4766 // Scan all new class loader data objects and new dependencies that were 4767 // introduced during concurrent marking. 4768 ResourceMark rm; 4769 GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds(); 4770 for (int i = 0; i < array->length(); i++) { 4771 par_mrias_cl.do_class_loader_data(array->at(i)); 4772 } 4773 4774 // We don't need to keep track of new CLDs anymore. 4775 ClassLoaderDataGraph::remember_new_clds(false); 4776 4777 _timer.stop(); 4778 if (PrintCMSStatistics != 0) { 4779 gclog_or_tty->print_cr( 4780 "Finished unhandled CLD scanning work in %dth thread: %3.3f sec", 4781 worker_id, _timer.seconds()); 4782 } 4783 } 4784 4785 // ---------- dirty klass scanning ---------- 4786 if (worker_id == 0) { // Single threaded at the moment. 4787 _timer.reset(); 4788 _timer.start(); 4789 4790 // Scan all classes that was dirtied during the concurrent marking phase. 4791 RemarkKlassClosure remark_klass_closure(&par_mrias_cl); 4792 ClassLoaderDataGraph::classes_do(&remark_klass_closure); 4793 4794 _timer.stop(); 4795 if (PrintCMSStatistics != 0) { 4796 gclog_or_tty->print_cr( 4797 "Finished dirty klass scanning work in %dth thread: %3.3f sec", 4798 worker_id, _timer.seconds()); 4799 } 4800 } 4801 4802 // We might have added oops to ClassLoaderData::_handles during the 4803 // concurrent marking phase. These oops point to newly allocated objects 4804 // that are guaranteed to be kept alive. Either by the direct allocation 4805 // code, or when the young collector processes the roots. Hence, 4806 // we don't have to revisit the _handles block during the remark phase. 4807 4808 // ---------- rescan dirty cards ------------ 4809 _timer.reset(); 4810 _timer.start(); 4811 4812 // Do the rescan tasks for each of the two spaces 4813 // (cms_space) in turn. 4814 // "worker_id" is passed to select the task_queue for "worker_id" 4815 do_dirty_card_rescan_tasks(_cms_space, worker_id, &par_mrias_cl); 4816 _timer.stop(); 4817 if (PrintCMSStatistics != 0) { 4818 gclog_or_tty->print_cr( 4819 "Finished dirty card rescan work in %dth thread: %3.3f sec", 4820 worker_id, _timer.seconds()); 4821 } 4822 4823 // ---------- steal work from other threads ... 4824 // ---------- ... and drain overflow list. 4825 _timer.reset(); 4826 _timer.start(); 4827 do_work_steal(worker_id, &par_mrias_cl, _collector->hash_seed(worker_id)); 4828 _timer.stop(); 4829 if (PrintCMSStatistics != 0) { 4830 gclog_or_tty->print_cr( 4831 "Finished work stealing in %dth thread: %3.3f sec", 4832 worker_id, _timer.seconds()); 4833 } 4834 } 4835 4836 // Note that parameter "i" is not used. 4837 void 4838 CMSParMarkTask::do_young_space_rescan(uint worker_id, 4839 OopsInGenClosure* cl, ContiguousSpace* space, 4840 HeapWord** chunk_array, size_t chunk_top) { 4841 // Until all tasks completed: 4842 // . claim an unclaimed task 4843 // . compute region boundaries corresponding to task claimed 4844 // using chunk_array 4845 // . par_oop_iterate(cl) over that region 4846 4847 ResourceMark rm; 4848 HandleMark hm; 4849 4850 SequentialSubTasksDone* pst = space->par_seq_tasks(); 4851 4852 uint nth_task = 0; 4853 uint n_tasks = pst->n_tasks(); 4854 4855 if (n_tasks > 0) { 4856 assert(pst->valid(), "Uninitialized use?"); 4857 HeapWord *start, *end; 4858 while (!pst->is_task_claimed(/* reference */ nth_task)) { 4859 // We claimed task # nth_task; compute its boundaries. 4860 if (chunk_top == 0) { // no samples were taken 4861 assert(nth_task == 0 && n_tasks == 1, "Can have only 1 eden task"); 4862 start = space->bottom(); 4863 end = space->top(); 4864 } else if (nth_task == 0) { 4865 start = space->bottom(); 4866 end = chunk_array[nth_task]; 4867 } else if (nth_task < (uint)chunk_top) { 4868 assert(nth_task >= 1, "Control point invariant"); 4869 start = chunk_array[nth_task - 1]; 4870 end = chunk_array[nth_task]; 4871 } else { 4872 assert(nth_task == (uint)chunk_top, "Control point invariant"); 4873 start = chunk_array[chunk_top - 1]; 4874 end = space->top(); 4875 } 4876 MemRegion mr(start, end); 4877 // Verify that mr is in space 4878 assert(mr.is_empty() || space->used_region().contains(mr), 4879 "Should be in space"); 4880 // Verify that "start" is an object boundary 4881 assert(mr.is_empty() || oop(mr.start())->is_oop(), 4882 "Should be an oop"); 4883 space->par_oop_iterate(mr, cl); 4884 } 4885 pst->all_tasks_completed(); 4886 } 4887 } 4888 4889 void 4890 CMSParRemarkTask::do_dirty_card_rescan_tasks( 4891 CompactibleFreeListSpace* sp, int i, 4892 Par_MarkRefsIntoAndScanClosure* cl) { 4893 // Until all tasks completed: 4894 // . claim an unclaimed task 4895 // . compute region boundaries corresponding to task claimed 4896 // . transfer dirty bits ct->mut for that region 4897 // . apply rescanclosure to dirty mut bits for that region 4898 4899 ResourceMark rm; 4900 HandleMark hm; 4901 4902 OopTaskQueue* work_q = work_queue(i); 4903 ModUnionClosure modUnionClosure(&(_collector->_modUnionTable)); 4904 // CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! 4905 // CAUTION: This closure has state that persists across calls to 4906 // the work method dirty_range_iterate_clear() in that it has 4907 // embedded in it a (subtype of) UpwardsObjectClosure. The 4908 // use of that state in the embedded UpwardsObjectClosure instance 4909 // assumes that the cards are always iterated (even if in parallel 4910 // by several threads) in monotonically increasing order per each 4911 // thread. This is true of the implementation below which picks 4912 // card ranges (chunks) in monotonically increasing order globally 4913 // and, a-fortiori, in monotonically increasing order per thread 4914 // (the latter order being a subsequence of the former). 4915 // If the work code below is ever reorganized into a more chaotic 4916 // work-partitioning form than the current "sequential tasks" 4917 // paradigm, the use of that persistent state will have to be 4918 // revisited and modified appropriately. See also related 4919 // bug 4756801 work on which should examine this code to make 4920 // sure that the changes there do not run counter to the 4921 // assumptions made here and necessary for correctness and 4922 // efficiency. Note also that this code might yield inefficient 4923 // behavior in the case of very large objects that span one or 4924 // more work chunks. Such objects would potentially be scanned 4925 // several times redundantly. Work on 4756801 should try and 4926 // address that performance anomaly if at all possible. XXX 4927 MemRegion full_span = _collector->_span; 4928 CMSBitMap* bm = &(_collector->_markBitMap); // shared 4929 MarkFromDirtyCardsClosure 4930 greyRescanClosure(_collector, full_span, // entire span of interest 4931 sp, bm, work_q, cl); 4932 4933 SequentialSubTasksDone* pst = sp->conc_par_seq_tasks(); 4934 assert(pst->valid(), "Uninitialized use?"); 4935 uint nth_task = 0; 4936 const int alignment = CardTableModRefBS::card_size * BitsPerWord; 4937 MemRegion span = sp->used_region(); 4938 HeapWord* start_addr = span.start(); 4939 HeapWord* end_addr = (HeapWord*)round_to((intptr_t)span.end(), 4940 alignment); 4941 const size_t chunk_size = sp->rescan_task_size(); // in HeapWord units 4942 assert((HeapWord*)round_to((intptr_t)start_addr, alignment) == 4943 start_addr, "Check alignment"); 4944 assert((size_t)round_to((intptr_t)chunk_size, alignment) == 4945 chunk_size, "Check alignment"); 4946 4947 while (!pst->is_task_claimed(/* reference */ nth_task)) { 4948 // Having claimed the nth_task, compute corresponding mem-region, 4949 // which is a-fortiori aligned correctly (i.e. at a MUT boundary). 4950 // The alignment restriction ensures that we do not need any 4951 // synchronization with other gang-workers while setting or 4952 // clearing bits in thus chunk of the MUT. 4953 MemRegion this_span = MemRegion(start_addr + nth_task*chunk_size, 4954 start_addr + (nth_task+1)*chunk_size); 4955 // The last chunk's end might be way beyond end of the 4956 // used region. In that case pull back appropriately. 4957 if (this_span.end() > end_addr) { 4958 this_span.set_end(end_addr); 4959 assert(!this_span.is_empty(), "Program logic (calculation of n_tasks)"); 4960 } 4961 // Iterate over the dirty cards covering this chunk, marking them 4962 // precleaned, and setting the corresponding bits in the mod union 4963 // table. Since we have been careful to partition at Card and MUT-word 4964 // boundaries no synchronization is needed between parallel threads. 4965 _collector->_ct->ct_bs()->dirty_card_iterate(this_span, 4966 &modUnionClosure); 4967 4968 // Having transferred these marks into the modUnionTable, 4969 // rescan the marked objects on the dirty cards in the modUnionTable. 4970 // Even if this is at a synchronous collection, the initial marking 4971 // may have been done during an asynchronous collection so there 4972 // may be dirty bits in the mod-union table. 4973 _collector->_modUnionTable.dirty_range_iterate_clear( 4974 this_span, &greyRescanClosure); 4975 _collector->_modUnionTable.verifyNoOneBitsInRange( 4976 this_span.start(), 4977 this_span.end()); 4978 } 4979 pst->all_tasks_completed(); // declare that i am done 4980 } 4981 4982 // . see if we can share work_queues with ParNew? XXX 4983 void 4984 CMSParRemarkTask::do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl, 4985 int* seed) { 4986 OopTaskQueue* work_q = work_queue(i); 4987 NOT_PRODUCT(int num_steals = 0;) 4988 oop obj_to_scan; 4989 CMSBitMap* bm = &(_collector->_markBitMap); 4990 4991 while (true) { 4992 // Completely finish any left over work from (an) earlier round(s) 4993 cl->trim_queue(0); 4994 size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4, 4995 (size_t)ParGCDesiredObjsFromOverflowList); 4996 // Now check if there's any work in the overflow list 4997 // Passing ParallelGCThreads as the third parameter, no_of_gc_threads, 4998 // only affects the number of attempts made to get work from the 4999 // overflow list and does not affect the number of workers. Just 5000 // pass ParallelGCThreads so this behavior is unchanged. 5001 if (_collector->par_take_from_overflow_list(num_from_overflow_list, 5002 work_q, 5003 ParallelGCThreads)) { 5004 // found something in global overflow list; 5005 // not yet ready to go stealing work from others. 5006 // We'd like to assert(work_q->size() != 0, ...) 5007 // because we just took work from the overflow list, 5008 // but of course we can't since all of that could have 5009 // been already stolen from us. 5010 // "He giveth and He taketh away." 5011 continue; 5012 } 5013 // Verify that we have no work before we resort to stealing 5014 assert(work_q->size() == 0, "Have work, shouldn't steal"); 5015 // Try to steal from other queues that have work 5016 if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) { 5017 NOT_PRODUCT(num_steals++;) 5018 assert(obj_to_scan->is_oop(), "Oops, not an oop!"); 5019 assert(bm->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?"); 5020 // Do scanning work 5021 obj_to_scan->oop_iterate(cl); 5022 // Loop around, finish this work, and try to steal some more 5023 } else if (terminator()->offer_termination()) { 5024 break; // nirvana from the infinite cycle 5025 } 5026 } 5027 NOT_PRODUCT( 5028 if (PrintCMSStatistics != 0) { 5029 gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals); 5030 } 5031 ) 5032 assert(work_q->size() == 0 && _collector->overflow_list_is_empty(), 5033 "Else our work is not yet done"); 5034 } 5035 5036 // Record object boundaries in _eden_chunk_array by sampling the eden 5037 // top in the slow-path eden object allocation code path and record 5038 // the boundaries, if CMSEdenChunksRecordAlways is true. If 5039 // CMSEdenChunksRecordAlways is false, we use the other asynchronous 5040 // sampling in sample_eden() that activates during the part of the 5041 // preclean phase. 5042 void CMSCollector::sample_eden_chunk() { 5043 if (CMSEdenChunksRecordAlways && _eden_chunk_array != NULL) { 5044 if (_eden_chunk_lock->try_lock()) { 5045 // Record a sample. This is the critical section. The contents 5046 // of the _eden_chunk_array have to be non-decreasing in the 5047 // address order. 5048 _eden_chunk_array[_eden_chunk_index] = *_top_addr; 5049 assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr, 5050 "Unexpected state of Eden"); 5051 if (_eden_chunk_index == 0 || 5052 ((_eden_chunk_array[_eden_chunk_index] > _eden_chunk_array[_eden_chunk_index-1]) && 5053 (pointer_delta(_eden_chunk_array[_eden_chunk_index], 5054 _eden_chunk_array[_eden_chunk_index-1]) >= CMSSamplingGrain))) { 5055 _eden_chunk_index++; // commit sample 5056 } 5057 _eden_chunk_lock->unlock(); 5058 } 5059 } 5060 } 5061 5062 // Return a thread-local PLAB recording array, as appropriate. 5063 void* CMSCollector::get_data_recorder(int thr_num) { 5064 if (_survivor_plab_array != NULL && 5065 (CMSPLABRecordAlways || 5066 (_collectorState > Marking && _collectorState < FinalMarking))) { 5067 assert(thr_num < (int)ParallelGCThreads, "thr_num is out of bounds"); 5068 ChunkArray* ca = &_survivor_plab_array[thr_num]; 5069 ca->reset(); // clear it so that fresh data is recorded 5070 return (void*) ca; 5071 } else { 5072 return NULL; 5073 } 5074 } 5075 5076 // Reset all the thread-local PLAB recording arrays 5077 void CMSCollector::reset_survivor_plab_arrays() { 5078 for (uint i = 0; i < ParallelGCThreads; i++) { 5079 _survivor_plab_array[i].reset(); 5080 } 5081 } 5082 5083 // Merge the per-thread plab arrays into the global survivor chunk 5084 // array which will provide the partitioning of the survivor space 5085 // for CMS initial scan and rescan. 5086 void CMSCollector::merge_survivor_plab_arrays(ContiguousSpace* surv, 5087 int no_of_gc_threads) { 5088 assert(_survivor_plab_array != NULL, "Error"); 5089 assert(_survivor_chunk_array != NULL, "Error"); 5090 assert(_collectorState == FinalMarking || 5091 (CMSParallelInitialMarkEnabled && _collectorState == InitialMarking), "Error"); 5092 for (int j = 0; j < no_of_gc_threads; j++) { 5093 _cursor[j] = 0; 5094 } 5095 HeapWord* top = surv->top(); 5096 size_t i; 5097 for (i = 0; i < _survivor_chunk_capacity; i++) { // all sca entries 5098 HeapWord* min_val = top; // Higher than any PLAB address 5099 uint min_tid = 0; // position of min_val this round 5100 for (int j = 0; j < no_of_gc_threads; j++) { 5101 ChunkArray* cur_sca = &_survivor_plab_array[j]; 5102 if (_cursor[j] == cur_sca->end()) { 5103 continue; 5104 } 5105 assert(_cursor[j] < cur_sca->end(), "ctl pt invariant"); 5106 HeapWord* cur_val = cur_sca->nth(_cursor[j]); 5107 assert(surv->used_region().contains(cur_val), "Out of bounds value"); 5108 if (cur_val < min_val) { 5109 min_tid = j; 5110 min_val = cur_val; 5111 } else { 5112 assert(cur_val < top, "All recorded addresses should be less"); 5113 } 5114 } 5115 // At this point min_val and min_tid are respectively 5116 // the least address in _survivor_plab_array[j]->nth(_cursor[j]) 5117 // and the thread (j) that witnesses that address. 5118 // We record this address in the _survivor_chunk_array[i] 5119 // and increment _cursor[min_tid] prior to the next round i. 5120 if (min_val == top) { 5121 break; 5122 } 5123 _survivor_chunk_array[i] = min_val; 5124 _cursor[min_tid]++; 5125 } 5126 // We are all done; record the size of the _survivor_chunk_array 5127 _survivor_chunk_index = i; // exclusive: [0, i) 5128 if (PrintCMSStatistics > 0) { 5129 gclog_or_tty->print(" (Survivor:" SIZE_FORMAT "chunks) ", i); 5130 } 5131 // Verify that we used up all the recorded entries 5132 #ifdef ASSERT 5133 size_t total = 0; 5134 for (int j = 0; j < no_of_gc_threads; j++) { 5135 assert(_cursor[j] == _survivor_plab_array[j].end(), "Ctl pt invariant"); 5136 total += _cursor[j]; 5137 } 5138 assert(total == _survivor_chunk_index, "Ctl Pt Invariant"); 5139 // Check that the merged array is in sorted order 5140 if (total > 0) { 5141 for (size_t i = 0; i < total - 1; i++) { 5142 if (PrintCMSStatistics > 0) { 5143 gclog_or_tty->print(" (chunk" SIZE_FORMAT ":" INTPTR_FORMAT ") ", 5144 i, _survivor_chunk_array[i]); 5145 } 5146 assert(_survivor_chunk_array[i] < _survivor_chunk_array[i+1], 5147 "Not sorted"); 5148 } 5149 } 5150 #endif // ASSERT 5151 } 5152 5153 // Set up the space's par_seq_tasks structure for work claiming 5154 // for parallel initial scan and rescan of young gen. 5155 // See ParRescanTask where this is currently used. 5156 void 5157 CMSCollector:: 5158 initialize_sequential_subtasks_for_young_gen_rescan(int n_threads) { 5159 assert(n_threads > 0, "Unexpected n_threads argument"); 5160 DefNewGeneration* dng = _young_gen->as_DefNewGeneration(); 5161 5162 // Eden space 5163 if (!dng->eden()->is_empty()) { 5164 SequentialSubTasksDone* pst = dng->eden()->par_seq_tasks(); 5165 assert(!pst->valid(), "Clobbering existing data?"); 5166 // Each valid entry in [0, _eden_chunk_index) represents a task. 5167 size_t n_tasks = _eden_chunk_index + 1; 5168 assert(n_tasks == 1 || _eden_chunk_array != NULL, "Error"); 5169 // Sets the condition for completion of the subtask (how many threads 5170 // need to finish in order to be done). 5171 pst->set_n_threads(n_threads); 5172 pst->set_n_tasks((int)n_tasks); 5173 } 5174 5175 // Merge the survivor plab arrays into _survivor_chunk_array 5176 if (_survivor_plab_array != NULL) { 5177 merge_survivor_plab_arrays(dng->from(), n_threads); 5178 } else { 5179 assert(_survivor_chunk_index == 0, "Error"); 5180 } 5181 5182 // To space 5183 { 5184 SequentialSubTasksDone* pst = dng->to()->par_seq_tasks(); 5185 assert(!pst->valid(), "Clobbering existing data?"); 5186 // Sets the condition for completion of the subtask (how many threads 5187 // need to finish in order to be done). 5188 pst->set_n_threads(n_threads); 5189 pst->set_n_tasks(1); 5190 assert(pst->valid(), "Error"); 5191 } 5192 5193 // From space 5194 { 5195 SequentialSubTasksDone* pst = dng->from()->par_seq_tasks(); 5196 assert(!pst->valid(), "Clobbering existing data?"); 5197 size_t n_tasks = _survivor_chunk_index + 1; 5198 assert(n_tasks == 1 || _survivor_chunk_array != NULL, "Error"); 5199 // Sets the condition for completion of the subtask (how many threads 5200 // need to finish in order to be done). 5201 pst->set_n_threads(n_threads); 5202 pst->set_n_tasks((int)n_tasks); 5203 assert(pst->valid(), "Error"); 5204 } 5205 } 5206 5207 // Parallel version of remark 5208 void CMSCollector::do_remark_parallel() { 5209 GenCollectedHeap* gch = GenCollectedHeap::heap(); 5210 FlexibleWorkGang* workers = gch->workers(); 5211 assert(workers != NULL, "Need parallel worker threads."); 5212 // Choose to use the number of GC workers most recently set 5213 // into "active_workers". If active_workers is not set, set it 5214 // to ParallelGCThreads. 5215 int n_workers = workers->active_workers(); 5216 if (n_workers == 0) { 5217 assert(n_workers > 0, "Should have been set during scavenge"); 5218 n_workers = ParallelGCThreads; 5219 workers->set_active_workers(n_workers); 5220 } 5221 CompactibleFreeListSpace* cms_space = _cmsGen->cmsSpace(); 5222 5223 CMSParRemarkTask tsk(this, 5224 cms_space, 5225 n_workers, workers, task_queues()); 5226 5227 // Set up for parallel process_roots work. 5228 gch->set_par_threads(n_workers); 5229 // We won't be iterating over the cards in the card table updating 5230 // the younger_gen cards, so we shouldn't call the following else 5231 // the verification code as well as subsequent younger_refs_iterate 5232 // code would get confused. XXX 5233 // gch->rem_set()->prepare_for_younger_refs_iterate(true); // parallel 5234 5235 // The young gen rescan work will not be done as part of 5236 // process_roots (which currently doesn't know how to 5237 // parallelize such a scan), but rather will be broken up into 5238 // a set of parallel tasks (via the sampling that the [abortable] 5239 // preclean phase did of eden, plus the [two] tasks of 5240 // scanning the [two] survivor spaces. Further fine-grain 5241 // parallelization of the scanning of the survivor spaces 5242 // themselves, and of precleaning of the younger gen itself 5243 // is deferred to the future. 5244 initialize_sequential_subtasks_for_young_gen_rescan(n_workers); 5245 5246 // The dirty card rescan work is broken up into a "sequence" 5247 // of parallel tasks (per constituent space) that are dynamically 5248 // claimed by the parallel threads. 5249 cms_space->initialize_sequential_subtasks_for_rescan(n_workers); 5250 5251 // It turns out that even when we're using 1 thread, doing the work in a 5252 // separate thread causes wide variance in run times. We can't help this 5253 // in the multi-threaded case, but we special-case n=1 here to get 5254 // repeatable measurements of the 1-thread overhead of the parallel code. 5255 if (n_workers > 1) { 5256 // Make refs discovery MT-safe, if it isn't already: it may not 5257 // necessarily be so, since it's possible that we are doing 5258 // ST marking. 5259 ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), true); 5260 GenCollectedHeap::StrongRootsScope srs(gch); 5261 workers->run_task(&tsk); 5262 } else { 5263 ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false); 5264 GenCollectedHeap::StrongRootsScope srs(gch); 5265 tsk.work(0); 5266 } 5267 5268 gch->set_par_threads(0); // 0 ==> non-parallel. 5269 // restore, single-threaded for now, any preserved marks 5270 // as a result of work_q overflow 5271 restore_preserved_marks_if_any(); 5272 } 5273 5274 // Non-parallel version of remark 5275 void CMSCollector::do_remark_non_parallel() { 5276 ResourceMark rm; 5277 HandleMark hm; 5278 GenCollectedHeap* gch = GenCollectedHeap::heap(); 5279 ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false); 5280 5281 MarkRefsIntoAndScanClosure 5282 mrias_cl(_span, ref_processor(), &_markBitMap, NULL /* not precleaning */, 5283 &_markStack, this, 5284 false /* should_yield */, false /* not precleaning */); 5285 MarkFromDirtyCardsClosure 5286 markFromDirtyCardsClosure(this, _span, 5287 NULL, // space is set further below 5288 &_markBitMap, &_markStack, &mrias_cl); 5289 { 5290 GCTraceTime t("grey object rescan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5291 // Iterate over the dirty cards, setting the corresponding bits in the 5292 // mod union table. 5293 { 5294 ModUnionClosure modUnionClosure(&_modUnionTable); 5295 _ct->ct_bs()->dirty_card_iterate( 5296 _cmsGen->used_region(), 5297 &modUnionClosure); 5298 } 5299 // Having transferred these marks into the modUnionTable, we just need 5300 // to rescan the marked objects on the dirty cards in the modUnionTable. 5301 // The initial marking may have been done during an asynchronous 5302 // collection so there may be dirty bits in the mod-union table. 5303 const int alignment = 5304 CardTableModRefBS::card_size * BitsPerWord; 5305 { 5306 // ... First handle dirty cards in CMS gen 5307 markFromDirtyCardsClosure.set_space(_cmsGen->cmsSpace()); 5308 MemRegion ur = _cmsGen->used_region(); 5309 HeapWord* lb = ur.start(); 5310 HeapWord* ub = (HeapWord*)round_to((intptr_t)ur.end(), alignment); 5311 MemRegion cms_span(lb, ub); 5312 _modUnionTable.dirty_range_iterate_clear(cms_span, 5313 &markFromDirtyCardsClosure); 5314 verify_work_stacks_empty(); 5315 if (PrintCMSStatistics != 0) { 5316 gclog_or_tty->print(" (re-scanned "SIZE_FORMAT" dirty cards in cms gen) ", 5317 markFromDirtyCardsClosure.num_dirty_cards()); 5318 } 5319 } 5320 } 5321 if (VerifyDuringGC && 5322 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) { 5323 HandleMark hm; // Discard invalid handles created during verification 5324 Universe::verify(); 5325 } 5326 { 5327 GCTraceTime t("root rescan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5328 5329 verify_work_stacks_empty(); 5330 5331 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel. 5332 GenCollectedHeap::StrongRootsScope srs(gch); 5333 5334 gch->gen_process_roots(_cmsGen->level(), 5335 true, // younger gens as roots 5336 false, // use the local StrongRootsScope 5337 SharedHeap::ScanningOption(roots_scanning_options()), 5338 should_unload_classes(), 5339 &mrias_cl, 5340 NULL, 5341 NULL); // The dirty klasses will be handled below 5342 5343 assert(should_unload_classes() 5344 || (roots_scanning_options() & SharedHeap::SO_AllCodeCache), 5345 "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops"); 5346 } 5347 5348 { 5349 GCTraceTime t("visit unhandled CLDs", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5350 5351 verify_work_stacks_empty(); 5352 5353 // Scan all class loader data objects that might have been introduced 5354 // during concurrent marking. 5355 ResourceMark rm; 5356 GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds(); 5357 for (int i = 0; i < array->length(); i++) { 5358 mrias_cl.do_class_loader_data(array->at(i)); 5359 } 5360 5361 // We don't need to keep track of new CLDs anymore. 5362 ClassLoaderDataGraph::remember_new_clds(false); 5363 5364 verify_work_stacks_empty(); 5365 } 5366 5367 { 5368 GCTraceTime t("dirty klass scan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5369 5370 verify_work_stacks_empty(); 5371 5372 RemarkKlassClosure remark_klass_closure(&mrias_cl); 5373 ClassLoaderDataGraph::classes_do(&remark_klass_closure); 5374 5375 verify_work_stacks_empty(); 5376 } 5377 5378 // We might have added oops to ClassLoaderData::_handles during the 5379 // concurrent marking phase. These oops point to newly allocated objects 5380 // that are guaranteed to be kept alive. Either by the direct allocation 5381 // code, or when the young collector processes the roots. Hence, 5382 // we don't have to revisit the _handles block during the remark phase. 5383 5384 verify_work_stacks_empty(); 5385 // Restore evacuated mark words, if any, used for overflow list links 5386 if (!CMSOverflowEarlyRestoration) { 5387 restore_preserved_marks_if_any(); 5388 } 5389 verify_overflow_empty(); 5390 } 5391 5392 //////////////////////////////////////////////////////// 5393 // Parallel Reference Processing Task Proxy Class 5394 //////////////////////////////////////////////////////// 5395 class CMSRefProcTaskProxy: public AbstractGangTaskWOopQueues { 5396 typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask; 5397 CMSCollector* _collector; 5398 CMSBitMap* _mark_bit_map; 5399 const MemRegion _span; 5400 ProcessTask& _task; 5401 5402 public: 5403 CMSRefProcTaskProxy(ProcessTask& task, 5404 CMSCollector* collector, 5405 const MemRegion& span, 5406 CMSBitMap* mark_bit_map, 5407 AbstractWorkGang* workers, 5408 OopTaskQueueSet* task_queues): 5409 // XXX Should superclass AGTWOQ also know about AWG since it knows 5410 // about the task_queues used by the AWG? Then it could initialize 5411 // the terminator() object. See 6984287. The set_for_termination() 5412 // below is a temporary band-aid for the regression in 6984287. 5413 AbstractGangTaskWOopQueues("Process referents by policy in parallel", 5414 task_queues), 5415 _task(task), 5416 _collector(collector), _span(span), _mark_bit_map(mark_bit_map) 5417 { 5418 assert(_collector->_span.equals(_span) && !_span.is_empty(), 5419 "Inconsistency in _span"); 5420 set_for_termination(workers->active_workers()); 5421 } 5422 5423 OopTaskQueueSet* task_queues() { return queues(); } 5424 5425 OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); } 5426 5427 void do_work_steal(int i, 5428 CMSParDrainMarkingStackClosure* drain, 5429 CMSParKeepAliveClosure* keep_alive, 5430 int* seed); 5431 5432 virtual void work(uint worker_id); 5433 }; 5434 5435 void CMSRefProcTaskProxy::work(uint worker_id) { 5436 ResourceMark rm; 5437 HandleMark hm; 5438 assert(_collector->_span.equals(_span), "Inconsistency in _span"); 5439 CMSParKeepAliveClosure par_keep_alive(_collector, _span, 5440 _mark_bit_map, 5441 work_queue(worker_id)); 5442 CMSParDrainMarkingStackClosure par_drain_stack(_collector, _span, 5443 _mark_bit_map, 5444 work_queue(worker_id)); 5445 CMSIsAliveClosure is_alive_closure(_span, _mark_bit_map); 5446 _task.work(worker_id, is_alive_closure, par_keep_alive, par_drain_stack); 5447 if (_task.marks_oops_alive()) { 5448 do_work_steal(worker_id, &par_drain_stack, &par_keep_alive, 5449 _collector->hash_seed(worker_id)); 5450 } 5451 assert(work_queue(worker_id)->size() == 0, "work_queue should be empty"); 5452 assert(_collector->_overflow_list == NULL, "non-empty _overflow_list"); 5453 } 5454 5455 class CMSRefEnqueueTaskProxy: public AbstractGangTask { 5456 typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask; 5457 EnqueueTask& _task; 5458 5459 public: 5460 CMSRefEnqueueTaskProxy(EnqueueTask& task) 5461 : AbstractGangTask("Enqueue reference objects in parallel"), 5462 _task(task) 5463 { } 5464 5465 virtual void work(uint worker_id) 5466 { 5467 _task.work(worker_id); 5468 } 5469 }; 5470 5471 CMSParKeepAliveClosure::CMSParKeepAliveClosure(CMSCollector* collector, 5472 MemRegion span, CMSBitMap* bit_map, OopTaskQueue* work_queue): 5473 _span(span), 5474 _bit_map(bit_map), 5475 _work_queue(work_queue), 5476 _mark_and_push(collector, span, bit_map, work_queue), 5477 _low_water_mark(MIN2((uint)(work_queue->max_elems()/4), 5478 (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads))) 5479 { } 5480 5481 // . see if we can share work_queues with ParNew? XXX 5482 void CMSRefProcTaskProxy::do_work_steal(int i, 5483 CMSParDrainMarkingStackClosure* drain, 5484 CMSParKeepAliveClosure* keep_alive, 5485 int* seed) { 5486 OopTaskQueue* work_q = work_queue(i); 5487 NOT_PRODUCT(int num_steals = 0;) 5488 oop obj_to_scan; 5489 5490 while (true) { 5491 // Completely finish any left over work from (an) earlier round(s) 5492 drain->trim_queue(0); 5493 size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4, 5494 (size_t)ParGCDesiredObjsFromOverflowList); 5495 // Now check if there's any work in the overflow list 5496 // Passing ParallelGCThreads as the third parameter, no_of_gc_threads, 5497 // only affects the number of attempts made to get work from the 5498 // overflow list and does not affect the number of workers. Just 5499 // pass ParallelGCThreads so this behavior is unchanged. 5500 if (_collector->par_take_from_overflow_list(num_from_overflow_list, 5501 work_q, 5502 ParallelGCThreads)) { 5503 // Found something in global overflow list; 5504 // not yet ready to go stealing work from others. 5505 // We'd like to assert(work_q->size() != 0, ...) 5506 // because we just took work from the overflow list, 5507 // but of course we can't, since all of that might have 5508 // been already stolen from us. 5509 continue; 5510 } 5511 // Verify that we have no work before we resort to stealing 5512 assert(work_q->size() == 0, "Have work, shouldn't steal"); 5513 // Try to steal from other queues that have work 5514 if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) { 5515 NOT_PRODUCT(num_steals++;) 5516 assert(obj_to_scan->is_oop(), "Oops, not an oop!"); 5517 assert(_mark_bit_map->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?"); 5518 // Do scanning work 5519 obj_to_scan->oop_iterate(keep_alive); 5520 // Loop around, finish this work, and try to steal some more 5521 } else if (terminator()->offer_termination()) { 5522 break; // nirvana from the infinite cycle 5523 } 5524 } 5525 NOT_PRODUCT( 5526 if (PrintCMSStatistics != 0) { 5527 gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals); 5528 } 5529 ) 5530 } 5531 5532 void CMSRefProcTaskExecutor::execute(ProcessTask& task) 5533 { 5534 GenCollectedHeap* gch = GenCollectedHeap::heap(); 5535 FlexibleWorkGang* workers = gch->workers(); 5536 assert(workers != NULL, "Need parallel worker threads."); 5537 CMSRefProcTaskProxy rp_task(task, &_collector, 5538 _collector.ref_processor()->span(), 5539 _collector.markBitMap(), 5540 workers, _collector.task_queues()); 5541 workers->run_task(&rp_task); 5542 } 5543 5544 void CMSRefProcTaskExecutor::execute(EnqueueTask& task) 5545 { 5546 5547 GenCollectedHeap* gch = GenCollectedHeap::heap(); 5548 FlexibleWorkGang* workers = gch->workers(); 5549 assert(workers != NULL, "Need parallel worker threads."); 5550 CMSRefEnqueueTaskProxy enq_task(task); 5551 workers->run_task(&enq_task); 5552 } 5553 5554 void CMSCollector::refProcessingWork() { 5555 ResourceMark rm; 5556 HandleMark hm; 5557 5558 ReferenceProcessor* rp = ref_processor(); 5559 assert(rp->span().equals(_span), "Spans should be equal"); 5560 assert(!rp->enqueuing_is_done(), "Enqueuing should not be complete"); 5561 // Process weak references. 5562 rp->setup_policy(false); 5563 verify_work_stacks_empty(); 5564 5565 CMSKeepAliveClosure cmsKeepAliveClosure(this, _span, &_markBitMap, 5566 &_markStack, false /* !preclean */); 5567 CMSDrainMarkingStackClosure cmsDrainMarkingStackClosure(this, 5568 _span, &_markBitMap, &_markStack, 5569 &cmsKeepAliveClosure, false /* !preclean */); 5570 { 5571 GCTraceTime t("weak refs processing", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5572 5573 ReferenceProcessorStats stats; 5574 if (rp->processing_is_mt()) { 5575 // Set the degree of MT here. If the discovery is done MT, there 5576 // may have been a different number of threads doing the discovery 5577 // and a different number of discovered lists may have Ref objects. 5578 // That is OK as long as the Reference lists are balanced (see 5579 // balance_all_queues() and balance_queues()). 5580 GenCollectedHeap* gch = GenCollectedHeap::heap(); 5581 int active_workers = ParallelGCThreads; 5582 FlexibleWorkGang* workers = gch->workers(); 5583 if (workers != NULL) { 5584 active_workers = workers->active_workers(); 5585 // The expectation is that active_workers will have already 5586 // been set to a reasonable value. If it has not been set, 5587 // investigate. 5588 assert(active_workers > 0, "Should have been set during scavenge"); 5589 } 5590 rp->set_active_mt_degree(active_workers); 5591 CMSRefProcTaskExecutor task_executor(*this); 5592 stats = rp->process_discovered_references(&_is_alive_closure, 5593 &cmsKeepAliveClosure, 5594 &cmsDrainMarkingStackClosure, 5595 &task_executor, 5596 _gc_timer_cm, 5597 _gc_tracer_cm->gc_id()); 5598 } else { 5599 stats = rp->process_discovered_references(&_is_alive_closure, 5600 &cmsKeepAliveClosure, 5601 &cmsDrainMarkingStackClosure, 5602 NULL, 5603 _gc_timer_cm, 5604 _gc_tracer_cm->gc_id()); 5605 } 5606 _gc_tracer_cm->report_gc_reference_stats(stats); 5607 5608 } 5609 5610 // This is the point where the entire marking should have completed. 5611 verify_work_stacks_empty(); 5612 5613 if (should_unload_classes()) { 5614 { 5615 GCTraceTime t("class unloading", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5616 5617 // Unload classes and purge the SystemDictionary. 5618 bool purged_class = SystemDictionary::do_unloading(&_is_alive_closure); 5619 5620 // Unload nmethods. 5621 CodeCache::do_unloading(&_is_alive_closure, purged_class); 5622 5623 // Prune dead klasses from subklass/sibling/implementor lists. 5624 Klass::clean_weak_klass_links(&_is_alive_closure); 5625 } 5626 5627 { 5628 GCTraceTime t("scrub symbol table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5629 // Clean up unreferenced symbols in symbol table. 5630 SymbolTable::unlink(); 5631 } 5632 5633 { 5634 GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5635 // Delete entries for dead interned strings. 5636 StringTable::unlink(&_is_alive_closure); 5637 } 5638 } 5639 5640 5641 // Restore any preserved marks as a result of mark stack or 5642 // work queue overflow 5643 restore_preserved_marks_if_any(); // done single-threaded for now 5644 5645 rp->set_enqueuing_is_done(true); 5646 if (rp->processing_is_mt()) { 5647 rp->balance_all_queues(); 5648 CMSRefProcTaskExecutor task_executor(*this); 5649 rp->enqueue_discovered_references(&task_executor); 5650 } else { 5651 rp->enqueue_discovered_references(NULL); 5652 } 5653 rp->verify_no_references_recorded(); 5654 assert(!rp->discovery_enabled(), "should have been disabled"); 5655 } 5656 5657 #ifndef PRODUCT 5658 void CMSCollector::check_correct_thread_executing() { 5659 Thread* t = Thread::current(); 5660 // Only the VM thread or the CMS thread should be here. 5661 assert(t->is_ConcurrentGC_thread() || t->is_VM_thread(), 5662 "Unexpected thread type"); 5663 // If this is the vm thread, the foreground process 5664 // should not be waiting. Note that _foregroundGCIsActive is 5665 // true while the foreground collector is waiting. 5666 if (_foregroundGCShouldWait) { 5667 // We cannot be the VM thread 5668 assert(t->is_ConcurrentGC_thread(), 5669 "Should be CMS thread"); 5670 } else { 5671 // We can be the CMS thread only if we are in a stop-world 5672 // phase of CMS collection. 5673 if (t->is_ConcurrentGC_thread()) { 5674 assert(_collectorState == InitialMarking || 5675 _collectorState == FinalMarking, 5676 "Should be a stop-world phase"); 5677 // The CMS thread should be holding the CMS_token. 5678 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 5679 "Potential interference with concurrently " 5680 "executing VM thread"); 5681 } 5682 } 5683 } 5684 #endif 5685 5686 void CMSCollector::sweep() { 5687 assert(_collectorState == Sweeping, "just checking"); 5688 check_correct_thread_executing(); 5689 verify_work_stacks_empty(); 5690 verify_overflow_empty(); 5691 increment_sweep_count(); 5692 TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause()); 5693 5694 _inter_sweep_timer.stop(); 5695 _inter_sweep_estimate.sample(_inter_sweep_timer.seconds()); 5696 5697 assert(!_intra_sweep_timer.is_active(), "Should not be active"); 5698 _intra_sweep_timer.reset(); 5699 _intra_sweep_timer.start(); 5700 { 5701 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 5702 CMSPhaseAccounting pa(this, "sweep", _gc_tracer_cm->gc_id(), !PrintGCDetails); 5703 // First sweep the old gen 5704 { 5705 CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock(), 5706 bitMapLock()); 5707 sweepWork(_cmsGen); 5708 } 5709 5710 // Update Universe::_heap_*_at_gc figures. 5711 // We need all the free list locks to make the abstract state 5712 // transition from Sweeping to Resetting. See detailed note 5713 // further below. 5714 { 5715 CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock()); 5716 // Update heap occupancy information which is used as 5717 // input to soft ref clearing policy at the next gc. 5718 Universe::update_heap_info_at_gc(); 5719 _collectorState = Resizing; 5720 } 5721 } 5722 verify_work_stacks_empty(); 5723 verify_overflow_empty(); 5724 5725 if (should_unload_classes()) { 5726 // Delay purge to the beginning of the next safepoint. Metaspace::contains 5727 // requires that the virtual spaces are stable and not deleted. 5728 ClassLoaderDataGraph::set_should_purge(true); 5729 } 5730 5731 _intra_sweep_timer.stop(); 5732 _intra_sweep_estimate.sample(_intra_sweep_timer.seconds()); 5733 5734 _inter_sweep_timer.reset(); 5735 _inter_sweep_timer.start(); 5736 5737 // We need to use a monotonically non-decreasing time in ms 5738 // or we will see time-warp warnings and os::javaTimeMillis() 5739 // does not guarantee monotonicity. 5740 jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC; 5741 update_time_of_last_gc(now); 5742 5743 // NOTE on abstract state transitions: 5744 // Mutators allocate-live and/or mark the mod-union table dirty 5745 // based on the state of the collection. The former is done in 5746 // the interval [Marking, Sweeping] and the latter in the interval 5747 // [Marking, Sweeping). Thus the transitions into the Marking state 5748 // and out of the Sweeping state must be synchronously visible 5749 // globally to the mutators. 5750 // The transition into the Marking state happens with the world 5751 // stopped so the mutators will globally see it. Sweeping is 5752 // done asynchronously by the background collector so the transition 5753 // from the Sweeping state to the Resizing state must be done 5754 // under the freelistLock (as is the check for whether to 5755 // allocate-live and whether to dirty the mod-union table). 5756 assert(_collectorState == Resizing, "Change of collector state to" 5757 " Resizing must be done under the freelistLocks (plural)"); 5758 5759 // Now that sweeping has been completed, we clear 5760 // the incremental_collection_failed flag, 5761 // thus inviting a younger gen collection to promote into 5762 // this generation. If such a promotion may still fail, 5763 // the flag will be set again when a young collection is 5764 // attempted. 5765 GenCollectedHeap* gch = GenCollectedHeap::heap(); 5766 gch->clear_incremental_collection_failed(); // Worth retrying as fresh space may have been freed up 5767 gch->update_full_collections_completed(_collection_count_start); 5768 } 5769 5770 // FIX ME!!! Looks like this belongs in CFLSpace, with 5771 // CMSGen merely delegating to it. 5772 void ConcurrentMarkSweepGeneration::setNearLargestChunk() { 5773 double nearLargestPercent = FLSLargestBlockCoalesceProximity; 5774 HeapWord* minAddr = _cmsSpace->bottom(); 5775 HeapWord* largestAddr = 5776 (HeapWord*) _cmsSpace->dictionary()->find_largest_dict(); 5777 if (largestAddr == NULL) { 5778 // The dictionary appears to be empty. In this case 5779 // try to coalesce at the end of the heap. 5780 largestAddr = _cmsSpace->end(); 5781 } 5782 size_t largestOffset = pointer_delta(largestAddr, minAddr); 5783 size_t nearLargestOffset = 5784 (size_t)((double)largestOffset * nearLargestPercent) - MinChunkSize; 5785 if (PrintFLSStatistics != 0) { 5786 gclog_or_tty->print_cr( 5787 "CMS: Large Block: " PTR_FORMAT ";" 5788 " Proximity: " PTR_FORMAT " -> " PTR_FORMAT, 5789 largestAddr, 5790 _cmsSpace->nearLargestChunk(), minAddr + nearLargestOffset); 5791 } 5792 _cmsSpace->set_nearLargestChunk(minAddr + nearLargestOffset); 5793 } 5794 5795 bool ConcurrentMarkSweepGeneration::isNearLargestChunk(HeapWord* addr) { 5796 return addr >= _cmsSpace->nearLargestChunk(); 5797 } 5798 5799 FreeChunk* ConcurrentMarkSweepGeneration::find_chunk_at_end() { 5800 return _cmsSpace->find_chunk_at_end(); 5801 } 5802 5803 void ConcurrentMarkSweepGeneration::update_gc_stats(int current_level, 5804 bool full) { 5805 // The next lower level has been collected. Gather any statistics 5806 // that are of interest at this point. 5807 if (!full && (current_level + 1) == level()) { 5808 // Gather statistics on the young generation collection. 5809 collector()->stats().record_gc0_end(used()); 5810 } 5811 } 5812 5813 void CMSCollector::sweepWork(ConcurrentMarkSweepGeneration* gen) { 5814 // We iterate over the space(s) underlying this generation, 5815 // checking the mark bit map to see if the bits corresponding 5816 // to specific blocks are marked or not. Blocks that are 5817 // marked are live and are not swept up. All remaining blocks 5818 // are swept up, with coalescing on-the-fly as we sweep up 5819 // contiguous free and/or garbage blocks: 5820 // We need to ensure that the sweeper synchronizes with allocators 5821 // and stop-the-world collectors. In particular, the following 5822 // locks are used: 5823 // . CMS token: if this is held, a stop the world collection cannot occur 5824 // . freelistLock: if this is held no allocation can occur from this 5825 // generation by another thread 5826 // . bitMapLock: if this is held, no other thread can access or update 5827 // 5828 5829 // Note that we need to hold the freelistLock if we use 5830 // block iterate below; else the iterator might go awry if 5831 // a mutator (or promotion) causes block contents to change 5832 // (for instance if the allocator divvies up a block). 5833 // If we hold the free list lock, for all practical purposes 5834 // young generation GC's can't occur (they'll usually need to 5835 // promote), so we might as well prevent all young generation 5836 // GC's while we do a sweeping step. For the same reason, we might 5837 // as well take the bit map lock for the entire duration 5838 5839 // check that we hold the requisite locks 5840 assert(have_cms_token(), "Should hold cms token"); 5841 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), "Should possess CMS token to sweep"); 5842 assert_lock_strong(gen->freelistLock()); 5843 assert_lock_strong(bitMapLock()); 5844 5845 assert(!_inter_sweep_timer.is_active(), "Was switched off in an outer context"); 5846 assert(_intra_sweep_timer.is_active(), "Was switched on in an outer context"); 5847 gen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()), 5848 _inter_sweep_estimate.padded_average(), 5849 _intra_sweep_estimate.padded_average()); 5850 gen->setNearLargestChunk(); 5851 5852 { 5853 SweepClosure sweepClosure(this, gen, &_markBitMap, CMSYield); 5854 gen->cmsSpace()->blk_iterate_careful(&sweepClosure); 5855 // We need to free-up/coalesce garbage/blocks from a 5856 // co-terminal free run. This is done in the SweepClosure 5857 // destructor; so, do not remove this scope, else the 5858 // end-of-sweep-census below will be off by a little bit. 5859 } 5860 gen->cmsSpace()->sweep_completed(); 5861 gen->cmsSpace()->endSweepFLCensus(sweep_count()); 5862 if (should_unload_classes()) { // unloaded classes this cycle, 5863 _concurrent_cycles_since_last_unload = 0; // ... reset count 5864 } else { // did not unload classes, 5865 _concurrent_cycles_since_last_unload++; // ... increment count 5866 } 5867 } 5868 5869 // Reset CMS data structures (for now just the marking bit map) 5870 // preparatory for the next cycle. 5871 void CMSCollector::reset(bool concurrent) { 5872 if (concurrent) { 5873 CMSTokenSyncWithLocks ts(true, bitMapLock()); 5874 5875 // If the state is not "Resetting", the foreground thread 5876 // has done a collection and the resetting. 5877 if (_collectorState != Resetting) { 5878 assert(_collectorState == Idling, "The state should only change" 5879 " because the foreground collector has finished the collection"); 5880 return; 5881 } 5882 5883 // Clear the mark bitmap (no grey objects to start with) 5884 // for the next cycle. 5885 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 5886 CMSPhaseAccounting cmspa(this, "reset", _gc_tracer_cm->gc_id(), !PrintGCDetails); 5887 5888 HeapWord* curAddr = _markBitMap.startWord(); 5889 while (curAddr < _markBitMap.endWord()) { 5890 size_t remaining = pointer_delta(_markBitMap.endWord(), curAddr); 5891 MemRegion chunk(curAddr, MIN2(CMSBitMapYieldQuantum, remaining)); 5892 _markBitMap.clear_large_range(chunk); 5893 if (ConcurrentMarkSweepThread::should_yield() && 5894 !foregroundGCIsActive() && 5895 CMSYield) { 5896 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 5897 "CMS thread should hold CMS token"); 5898 assert_lock_strong(bitMapLock()); 5899 bitMapLock()->unlock(); 5900 ConcurrentMarkSweepThread::desynchronize(true); 5901 stopTimer(); 5902 if (PrintCMSStatistics != 0) { 5903 incrementYields(); 5904 } 5905 5906 // See the comment in coordinator_yield() 5907 for (unsigned i = 0; i < CMSYieldSleepCount && 5908 ConcurrentMarkSweepThread::should_yield() && 5909 !CMSCollector::foregroundGCIsActive(); ++i) { 5910 os::sleep(Thread::current(), 1, false); 5911 } 5912 5913 ConcurrentMarkSweepThread::synchronize(true); 5914 bitMapLock()->lock_without_safepoint_check(); 5915 startTimer(); 5916 } 5917 curAddr = chunk.end(); 5918 } 5919 // A successful mostly concurrent collection has been done. 5920 // Because only the full (i.e., concurrent mode failure) collections 5921 // are being measured for gc overhead limits, clean the "near" flag 5922 // and count. 5923 size_policy()->reset_gc_overhead_limit_count(); 5924 _collectorState = Idling; 5925 } else { 5926 // already have the lock 5927 assert(_collectorState == Resetting, "just checking"); 5928 assert_lock_strong(bitMapLock()); 5929 _markBitMap.clear_all(); 5930 _collectorState = Idling; 5931 } 5932 5933 register_gc_end(); 5934 } 5935 5936 void CMSCollector::do_CMS_operation(CMS_op_type op, GCCause::Cause gc_cause) { 5937 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 5938 GCTraceTime t(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL, _gc_tracer_cm->gc_id()); 5939 TraceCollectorStats tcs(counters()); 5940 5941 switch (op) { 5942 case CMS_op_checkpointRootsInitial: { 5943 SvcGCMarker sgcm(SvcGCMarker::OTHER); 5944 checkpointRootsInitial(); 5945 if (PrintGC) { 5946 _cmsGen->printOccupancy("initial-mark"); 5947 } 5948 break; 5949 } 5950 case CMS_op_checkpointRootsFinal: { 5951 SvcGCMarker sgcm(SvcGCMarker::OTHER); 5952 checkpointRootsFinal(); 5953 if (PrintGC) { 5954 _cmsGen->printOccupancy("remark"); 5955 } 5956 break; 5957 } 5958 default: 5959 fatal("No such CMS_op"); 5960 } 5961 } 5962 5963 #ifndef PRODUCT 5964 size_t const CMSCollector::skip_header_HeapWords() { 5965 return FreeChunk::header_size(); 5966 } 5967 5968 // Try and collect here conditions that should hold when 5969 // CMS thread is exiting. The idea is that the foreground GC 5970 // thread should not be blocked if it wants to terminate 5971 // the CMS thread and yet continue to run the VM for a while 5972 // after that. 5973 void CMSCollector::verify_ok_to_terminate() const { 5974 assert(Thread::current()->is_ConcurrentGC_thread(), 5975 "should be called by CMS thread"); 5976 assert(!_foregroundGCShouldWait, "should be false"); 5977 // We could check here that all the various low-level locks 5978 // are not held by the CMS thread, but that is overkill; see 5979 // also CMSThread::verify_ok_to_terminate() where the CGC_lock 5980 // is checked. 5981 } 5982 #endif 5983 5984 size_t CMSCollector::block_size_using_printezis_bits(HeapWord* addr) const { 5985 assert(_markBitMap.isMarked(addr) && _markBitMap.isMarked(addr + 1), 5986 "missing Printezis mark?"); 5987 HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2); 5988 size_t size = pointer_delta(nextOneAddr + 1, addr); 5989 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 5990 "alignment problem"); 5991 assert(size >= 3, "Necessary for Printezis marks to work"); 5992 return size; 5993 } 5994 5995 // A variant of the above (block_size_using_printezis_bits()) except 5996 // that we return 0 if the P-bits are not yet set. 5997 size_t CMSCollector::block_size_if_printezis_bits(HeapWord* addr) const { 5998 if (_markBitMap.isMarked(addr + 1)) { 5999 assert(_markBitMap.isMarked(addr), "P-bit can be set only for marked objects"); 6000 HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2); 6001 size_t size = pointer_delta(nextOneAddr + 1, addr); 6002 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 6003 "alignment problem"); 6004 assert(size >= 3, "Necessary for Printezis marks to work"); 6005 return size; 6006 } 6007 return 0; 6008 } 6009 6010 HeapWord* CMSCollector::next_card_start_after_block(HeapWord* addr) const { 6011 size_t sz = 0; 6012 oop p = (oop)addr; 6013 if (p->klass_or_null() != NULL) { 6014 sz = CompactibleFreeListSpace::adjustObjectSize(p->size()); 6015 } else { 6016 sz = block_size_using_printezis_bits(addr); 6017 } 6018 assert(sz > 0, "size must be nonzero"); 6019 HeapWord* next_block = addr + sz; 6020 HeapWord* next_card = (HeapWord*)round_to((uintptr_t)next_block, 6021 CardTableModRefBS::card_size); 6022 assert(round_down((uintptr_t)addr, CardTableModRefBS::card_size) < 6023 round_down((uintptr_t)next_card, CardTableModRefBS::card_size), 6024 "must be different cards"); 6025 return next_card; 6026 } 6027 6028 6029 // CMS Bit Map Wrapper ///////////////////////////////////////// 6030 6031 // Construct a CMS bit map infrastructure, but don't create the 6032 // bit vector itself. That is done by a separate call CMSBitMap::allocate() 6033 // further below. 6034 CMSBitMap::CMSBitMap(int shifter, int mutex_rank, const char* mutex_name): 6035 _bm(), 6036 _shifter(shifter), 6037 _lock(mutex_rank >= 0 ? new Mutex(mutex_rank, mutex_name, true) : NULL) 6038 { 6039 _bmStartWord = 0; 6040 _bmWordSize = 0; 6041 } 6042 6043 bool CMSBitMap::allocate(MemRegion mr) { 6044 _bmStartWord = mr.start(); 6045 _bmWordSize = mr.word_size(); 6046 ReservedSpace brs(ReservedSpace::allocation_align_size_up( 6047 (_bmWordSize >> (_shifter + LogBitsPerByte)) + 1)); 6048 if (!brs.is_reserved()) { 6049 warning("CMS bit map allocation failure"); 6050 return false; 6051 } 6052 // For now we'll just commit all of the bit map up front. 6053 // Later on we'll try to be more parsimonious with swap. 6054 if (!_virtual_space.initialize(brs, brs.size())) { 6055 warning("CMS bit map backing store failure"); 6056 return false; 6057 } 6058 assert(_virtual_space.committed_size() == brs.size(), 6059 "didn't reserve backing store for all of CMS bit map?"); 6060 _bm.set_map((BitMap::bm_word_t*)_virtual_space.low()); 6061 assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >= 6062 _bmWordSize, "inconsistency in bit map sizing"); 6063 _bm.set_size(_bmWordSize >> _shifter); 6064 6065 // bm.clear(); // can we rely on getting zero'd memory? verify below 6066 assert(isAllClear(), 6067 "Expected zero'd memory from ReservedSpace constructor"); 6068 assert(_bm.size() == heapWordDiffToOffsetDiff(sizeInWords()), 6069 "consistency check"); 6070 return true; 6071 } 6072 6073 void CMSBitMap::dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl) { 6074 HeapWord *next_addr, *end_addr, *last_addr; 6075 assert_locked(); 6076 assert(covers(mr), "out-of-range error"); 6077 // XXX assert that start and end are appropriately aligned 6078 for (next_addr = mr.start(), end_addr = mr.end(); 6079 next_addr < end_addr; next_addr = last_addr) { 6080 MemRegion dirty_region = getAndClearMarkedRegion(next_addr, end_addr); 6081 last_addr = dirty_region.end(); 6082 if (!dirty_region.is_empty()) { 6083 cl->do_MemRegion(dirty_region); 6084 } else { 6085 assert(last_addr == end_addr, "program logic"); 6086 return; 6087 } 6088 } 6089 } 6090 6091 void CMSBitMap::print_on_error(outputStream* st, const char* prefix) const { 6092 _bm.print_on_error(st, prefix); 6093 } 6094 6095 #ifndef PRODUCT 6096 void CMSBitMap::assert_locked() const { 6097 CMSLockVerifier::assert_locked(lock()); 6098 } 6099 6100 bool CMSBitMap::covers(MemRegion mr) const { 6101 // assert(_bm.map() == _virtual_space.low(), "map inconsistency"); 6102 assert((size_t)_bm.size() == (_bmWordSize >> _shifter), 6103 "size inconsistency"); 6104 return (mr.start() >= _bmStartWord) && 6105 (mr.end() <= endWord()); 6106 } 6107 6108 bool CMSBitMap::covers(HeapWord* start, size_t size) const { 6109 return (start >= _bmStartWord && (start + size) <= endWord()); 6110 } 6111 6112 void CMSBitMap::verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) { 6113 // verify that there are no 1 bits in the interval [left, right) 6114 FalseBitMapClosure falseBitMapClosure; 6115 iterate(&falseBitMapClosure, left, right); 6116 } 6117 6118 void CMSBitMap::region_invariant(MemRegion mr) 6119 { 6120 assert_locked(); 6121 // mr = mr.intersection(MemRegion(_bmStartWord, _bmWordSize)); 6122 assert(!mr.is_empty(), "unexpected empty region"); 6123 assert(covers(mr), "mr should be covered by bit map"); 6124 // convert address range into offset range 6125 size_t start_ofs = heapWordToOffset(mr.start()); 6126 // Make sure that end() is appropriately aligned 6127 assert(mr.end() == (HeapWord*)round_to((intptr_t)mr.end(), 6128 (1 << (_shifter+LogHeapWordSize))), 6129 "Misaligned mr.end()"); 6130 size_t end_ofs = heapWordToOffset(mr.end()); 6131 assert(end_ofs > start_ofs, "Should mark at least one bit"); 6132 } 6133 6134 #endif 6135 6136 bool CMSMarkStack::allocate(size_t size) { 6137 // allocate a stack of the requisite depth 6138 ReservedSpace rs(ReservedSpace::allocation_align_size_up( 6139 size * sizeof(oop))); 6140 if (!rs.is_reserved()) { 6141 warning("CMSMarkStack allocation failure"); 6142 return false; 6143 } 6144 if (!_virtual_space.initialize(rs, rs.size())) { 6145 warning("CMSMarkStack backing store failure"); 6146 return false; 6147 } 6148 assert(_virtual_space.committed_size() == rs.size(), 6149 "didn't reserve backing store for all of CMS stack?"); 6150 _base = (oop*)(_virtual_space.low()); 6151 _index = 0; 6152 _capacity = size; 6153 NOT_PRODUCT(_max_depth = 0); 6154 return true; 6155 } 6156 6157 // XXX FIX ME !!! In the MT case we come in here holding a 6158 // leaf lock. For printing we need to take a further lock 6159 // which has lower rank. We need to recalibrate the two 6160 // lock-ranks involved in order to be able to print the 6161 // messages below. (Or defer the printing to the caller. 6162 // For now we take the expedient path of just disabling the 6163 // messages for the problematic case.) 6164 void CMSMarkStack::expand() { 6165 assert(_capacity <= MarkStackSizeMax, "stack bigger than permitted"); 6166 if (_capacity == MarkStackSizeMax) { 6167 if (_hit_limit++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) { 6168 // We print a warning message only once per CMS cycle. 6169 gclog_or_tty->print_cr(" (benign) Hit CMSMarkStack max size limit"); 6170 } 6171 return; 6172 } 6173 // Double capacity if possible 6174 size_t new_capacity = MIN2(_capacity*2, MarkStackSizeMax); 6175 // Do not give up existing stack until we have managed to 6176 // get the double capacity that we desired. 6177 ReservedSpace rs(ReservedSpace::allocation_align_size_up( 6178 new_capacity * sizeof(oop))); 6179 if (rs.is_reserved()) { 6180 // Release the backing store associated with old stack 6181 _virtual_space.release(); 6182 // Reinitialize virtual space for new stack 6183 if (!_virtual_space.initialize(rs, rs.size())) { 6184 fatal("Not enough swap for expanded marking stack"); 6185 } 6186 _base = (oop*)(_virtual_space.low()); 6187 _index = 0; 6188 _capacity = new_capacity; 6189 } else if (_failed_double++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) { 6190 // Failed to double capacity, continue; 6191 // we print a detail message only once per CMS cycle. 6192 gclog_or_tty->print(" (benign) Failed to expand marking stack from "SIZE_FORMAT"K to " 6193 SIZE_FORMAT"K", 6194 _capacity / K, new_capacity / K); 6195 } 6196 } 6197 6198 6199 // Closures 6200 // XXX: there seems to be a lot of code duplication here; 6201 // should refactor and consolidate common code. 6202 6203 // This closure is used to mark refs into the CMS generation in 6204 // the CMS bit map. Called at the first checkpoint. This closure 6205 // assumes that we do not need to re-mark dirty cards; if the CMS 6206 // generation on which this is used is not an oldest 6207 // generation then this will lose younger_gen cards! 6208 6209 MarkRefsIntoClosure::MarkRefsIntoClosure( 6210 MemRegion span, CMSBitMap* bitMap): 6211 _span(span), 6212 _bitMap(bitMap) 6213 { 6214 assert(_ref_processor == NULL, "deliberately left NULL"); 6215 assert(_bitMap->covers(_span), "_bitMap/_span mismatch"); 6216 } 6217 6218 void MarkRefsIntoClosure::do_oop(oop obj) { 6219 // if p points into _span, then mark corresponding bit in _markBitMap 6220 assert(obj->is_oop(), "expected an oop"); 6221 HeapWord* addr = (HeapWord*)obj; 6222 if (_span.contains(addr)) { 6223 // this should be made more efficient 6224 _bitMap->mark(addr); 6225 } 6226 } 6227 6228 void MarkRefsIntoClosure::do_oop(oop* p) { MarkRefsIntoClosure::do_oop_work(p); } 6229 void MarkRefsIntoClosure::do_oop(narrowOop* p) { MarkRefsIntoClosure::do_oop_work(p); } 6230 6231 Par_MarkRefsIntoClosure::Par_MarkRefsIntoClosure( 6232 MemRegion span, CMSBitMap* bitMap): 6233 _span(span), 6234 _bitMap(bitMap) 6235 { 6236 assert(_ref_processor == NULL, "deliberately left NULL"); 6237 assert(_bitMap->covers(_span), "_bitMap/_span mismatch"); 6238 } 6239 6240 void Par_MarkRefsIntoClosure::do_oop(oop obj) { 6241 // if p points into _span, then mark corresponding bit in _markBitMap 6242 assert(obj->is_oop(), "expected an oop"); 6243 HeapWord* addr = (HeapWord*)obj; 6244 if (_span.contains(addr)) { 6245 // this should be made more efficient 6246 _bitMap->par_mark(addr); 6247 } 6248 } 6249 6250 void Par_MarkRefsIntoClosure::do_oop(oop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); } 6251 void Par_MarkRefsIntoClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); } 6252 6253 // A variant of the above, used for CMS marking verification. 6254 MarkRefsIntoVerifyClosure::MarkRefsIntoVerifyClosure( 6255 MemRegion span, CMSBitMap* verification_bm, CMSBitMap* cms_bm): 6256 _span(span), 6257 _verification_bm(verification_bm), 6258 _cms_bm(cms_bm) 6259 { 6260 assert(_ref_processor == NULL, "deliberately left NULL"); 6261 assert(_verification_bm->covers(_span), "_verification_bm/_span mismatch"); 6262 } 6263 6264 void MarkRefsIntoVerifyClosure::do_oop(oop obj) { 6265 // if p points into _span, then mark corresponding bit in _markBitMap 6266 assert(obj->is_oop(), "expected an oop"); 6267 HeapWord* addr = (HeapWord*)obj; 6268 if (_span.contains(addr)) { 6269 _verification_bm->mark(addr); 6270 if (!_cms_bm->isMarked(addr)) { 6271 oop(addr)->print(); 6272 gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", addr); 6273 fatal("... aborting"); 6274 } 6275 } 6276 } 6277 6278 void MarkRefsIntoVerifyClosure::do_oop(oop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); } 6279 void MarkRefsIntoVerifyClosure::do_oop(narrowOop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); } 6280 6281 ////////////////////////////////////////////////// 6282 // MarkRefsIntoAndScanClosure 6283 ////////////////////////////////////////////////// 6284 6285 MarkRefsIntoAndScanClosure::MarkRefsIntoAndScanClosure(MemRegion span, 6286 ReferenceProcessor* rp, 6287 CMSBitMap* bit_map, 6288 CMSBitMap* mod_union_table, 6289 CMSMarkStack* mark_stack, 6290 CMSCollector* collector, 6291 bool should_yield, 6292 bool concurrent_precleaning): 6293 _collector(collector), 6294 _span(span), 6295 _bit_map(bit_map), 6296 _mark_stack(mark_stack), 6297 _pushAndMarkClosure(collector, span, rp, bit_map, mod_union_table, 6298 mark_stack, concurrent_precleaning), 6299 _yield(should_yield), 6300 _concurrent_precleaning(concurrent_precleaning), 6301 _freelistLock(NULL) 6302 { 6303 _ref_processor = rp; 6304 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 6305 } 6306 6307 // This closure is used to mark refs into the CMS generation at the 6308 // second (final) checkpoint, and to scan and transitively follow 6309 // the unmarked oops. It is also used during the concurrent precleaning 6310 // phase while scanning objects on dirty cards in the CMS generation. 6311 // The marks are made in the marking bit map and the marking stack is 6312 // used for keeping the (newly) grey objects during the scan. 6313 // The parallel version (Par_...) appears further below. 6314 void MarkRefsIntoAndScanClosure::do_oop(oop obj) { 6315 if (obj != NULL) { 6316 assert(obj->is_oop(), "expected an oop"); 6317 HeapWord* addr = (HeapWord*)obj; 6318 assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)"); 6319 assert(_collector->overflow_list_is_empty(), 6320 "overflow list should be empty"); 6321 if (_span.contains(addr) && 6322 !_bit_map->isMarked(addr)) { 6323 // mark bit map (object is now grey) 6324 _bit_map->mark(addr); 6325 // push on marking stack (stack should be empty), and drain the 6326 // stack by applying this closure to the oops in the oops popped 6327 // from the stack (i.e. blacken the grey objects) 6328 bool res = _mark_stack->push(obj); 6329 assert(res, "Should have space to push on empty stack"); 6330 do { 6331 oop new_oop = _mark_stack->pop(); 6332 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop"); 6333 assert(_bit_map->isMarked((HeapWord*)new_oop), 6334 "only grey objects on this stack"); 6335 // iterate over the oops in this oop, marking and pushing 6336 // the ones in CMS heap (i.e. in _span). 6337 new_oop->oop_iterate(&_pushAndMarkClosure); 6338 // check if it's time to yield 6339 do_yield_check(); 6340 } while (!_mark_stack->isEmpty() || 6341 (!_concurrent_precleaning && take_from_overflow_list())); 6342 // if marking stack is empty, and we are not doing this 6343 // during precleaning, then check the overflow list 6344 } 6345 assert(_mark_stack->isEmpty(), "post-condition (eager drainage)"); 6346 assert(_collector->overflow_list_is_empty(), 6347 "overflow list was drained above"); 6348 // We could restore evacuated mark words, if any, used for 6349 // overflow list links here because the overflow list is 6350 // provably empty here. That would reduce the maximum 6351 // size requirements for preserved_{oop,mark}_stack. 6352 // But we'll just postpone it until we are all done 6353 // so we can just stream through. 6354 if (!_concurrent_precleaning && CMSOverflowEarlyRestoration) { 6355 _collector->restore_preserved_marks_if_any(); 6356 assert(_collector->no_preserved_marks(), "No preserved marks"); 6357 } 6358 assert(!CMSOverflowEarlyRestoration || _collector->no_preserved_marks(), 6359 "All preserved marks should have been restored above"); 6360 } 6361 } 6362 6363 void MarkRefsIntoAndScanClosure::do_oop(oop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); } 6364 void MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); } 6365 6366 void MarkRefsIntoAndScanClosure::do_yield_work() { 6367 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 6368 "CMS thread should hold CMS token"); 6369 assert_lock_strong(_freelistLock); 6370 assert_lock_strong(_bit_map->lock()); 6371 // relinquish the free_list_lock and bitMaplock() 6372 _bit_map->lock()->unlock(); 6373 _freelistLock->unlock(); 6374 ConcurrentMarkSweepThread::desynchronize(true); 6375 _collector->stopTimer(); 6376 if (PrintCMSStatistics != 0) { 6377 _collector->incrementYields(); 6378 } 6379 6380 // See the comment in coordinator_yield() 6381 for (unsigned i = 0; 6382 i < CMSYieldSleepCount && 6383 ConcurrentMarkSweepThread::should_yield() && 6384 !CMSCollector::foregroundGCIsActive(); 6385 ++i) { 6386 os::sleep(Thread::current(), 1, false); 6387 } 6388 6389 ConcurrentMarkSweepThread::synchronize(true); 6390 _freelistLock->lock_without_safepoint_check(); 6391 _bit_map->lock()->lock_without_safepoint_check(); 6392 _collector->startTimer(); 6393 } 6394 6395 /////////////////////////////////////////////////////////// 6396 // Par_MarkRefsIntoAndScanClosure: a parallel version of 6397 // MarkRefsIntoAndScanClosure 6398 /////////////////////////////////////////////////////////// 6399 Par_MarkRefsIntoAndScanClosure::Par_MarkRefsIntoAndScanClosure( 6400 CMSCollector* collector, MemRegion span, ReferenceProcessor* rp, 6401 CMSBitMap* bit_map, OopTaskQueue* work_queue): 6402 _span(span), 6403 _bit_map(bit_map), 6404 _work_queue(work_queue), 6405 _low_water_mark(MIN2((uint)(work_queue->max_elems()/4), 6406 (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads))), 6407 _par_pushAndMarkClosure(collector, span, rp, bit_map, work_queue) 6408 { 6409 _ref_processor = rp; 6410 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 6411 } 6412 6413 // This closure is used to mark refs into the CMS generation at the 6414 // second (final) checkpoint, and to scan and transitively follow 6415 // the unmarked oops. The marks are made in the marking bit map and 6416 // the work_queue is used for keeping the (newly) grey objects during 6417 // the scan phase whence they are also available for stealing by parallel 6418 // threads. Since the marking bit map is shared, updates are 6419 // synchronized (via CAS). 6420 void Par_MarkRefsIntoAndScanClosure::do_oop(oop obj) { 6421 if (obj != NULL) { 6422 // Ignore mark word because this could be an already marked oop 6423 // that may be chained at the end of the overflow list. 6424 assert(obj->is_oop(true), "expected an oop"); 6425 HeapWord* addr = (HeapWord*)obj; 6426 if (_span.contains(addr) && 6427 !_bit_map->isMarked(addr)) { 6428 // mark bit map (object will become grey): 6429 // It is possible for several threads to be 6430 // trying to "claim" this object concurrently; 6431 // the unique thread that succeeds in marking the 6432 // object first will do the subsequent push on 6433 // to the work queue (or overflow list). 6434 if (_bit_map->par_mark(addr)) { 6435 // push on work_queue (which may not be empty), and trim the 6436 // queue to an appropriate length by applying this closure to 6437 // the oops in the oops popped from the stack (i.e. blacken the 6438 // grey objects) 6439 bool res = _work_queue->push(obj); 6440 assert(res, "Low water mark should be less than capacity?"); 6441 trim_queue(_low_water_mark); 6442 } // Else, another thread claimed the object 6443 } 6444 } 6445 } 6446 6447 void Par_MarkRefsIntoAndScanClosure::do_oop(oop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); } 6448 void Par_MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); } 6449 6450 // This closure is used to rescan the marked objects on the dirty cards 6451 // in the mod union table and the card table proper. 6452 size_t ScanMarkedObjectsAgainCarefullyClosure::do_object_careful_m( 6453 oop p, MemRegion mr) { 6454 6455 size_t size = 0; 6456 HeapWord* addr = (HeapWord*)p; 6457 DEBUG_ONLY(_collector->verify_work_stacks_empty();) 6458 assert(_span.contains(addr), "we are scanning the CMS generation"); 6459 // check if it's time to yield 6460 if (do_yield_check()) { 6461 // We yielded for some foreground stop-world work, 6462 // and we have been asked to abort this ongoing preclean cycle. 6463 return 0; 6464 } 6465 if (_bitMap->isMarked(addr)) { 6466 // it's marked; is it potentially uninitialized? 6467 if (p->klass_or_null() != NULL) { 6468 // an initialized object; ignore mark word in verification below 6469 // since we are running concurrent with mutators 6470 assert(p->is_oop(true), "should be an oop"); 6471 if (p->is_objArray()) { 6472 // objArrays are precisely marked; restrict scanning 6473 // to dirty cards only. 6474 size = CompactibleFreeListSpace::adjustObjectSize( 6475 p->oop_iterate(_scanningClosure, mr)); 6476 } else { 6477 // A non-array may have been imprecisely marked; we need 6478 // to scan object in its entirety. 6479 size = CompactibleFreeListSpace::adjustObjectSize( 6480 p->oop_iterate(_scanningClosure)); 6481 } 6482 #ifdef ASSERT 6483 size_t direct_size = 6484 CompactibleFreeListSpace::adjustObjectSize(p->size()); 6485 assert(size == direct_size, "Inconsistency in size"); 6486 assert(size >= 3, "Necessary for Printezis marks to work"); 6487 if (!_bitMap->isMarked(addr+1)) { 6488 _bitMap->verifyNoOneBitsInRange(addr+2, addr+size); 6489 } else { 6490 _bitMap->verifyNoOneBitsInRange(addr+2, addr+size-1); 6491 assert(_bitMap->isMarked(addr+size-1), 6492 "inconsistent Printezis mark"); 6493 } 6494 #endif // ASSERT 6495 } else { 6496 // An uninitialized object. 6497 assert(_bitMap->isMarked(addr+1), "missing Printezis mark?"); 6498 HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2); 6499 size = pointer_delta(nextOneAddr + 1, addr); 6500 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 6501 "alignment problem"); 6502 // Note that pre-cleaning needn't redirty the card. OopDesc::set_klass() 6503 // will dirty the card when the klass pointer is installed in the 6504 // object (signaling the completion of initialization). 6505 } 6506 } else { 6507 // Either a not yet marked object or an uninitialized object 6508 if (p->klass_or_null() == NULL) { 6509 // An uninitialized object, skip to the next card, since 6510 // we may not be able to read its P-bits yet. 6511 assert(size == 0, "Initial value"); 6512 } else { 6513 // An object not (yet) reached by marking: we merely need to 6514 // compute its size so as to go look at the next block. 6515 assert(p->is_oop(true), "should be an oop"); 6516 size = CompactibleFreeListSpace::adjustObjectSize(p->size()); 6517 } 6518 } 6519 DEBUG_ONLY(_collector->verify_work_stacks_empty();) 6520 return size; 6521 } 6522 6523 void ScanMarkedObjectsAgainCarefullyClosure::do_yield_work() { 6524 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 6525 "CMS thread should hold CMS token"); 6526 assert_lock_strong(_freelistLock); 6527 assert_lock_strong(_bitMap->lock()); 6528 // relinquish the free_list_lock and bitMaplock() 6529 _bitMap->lock()->unlock(); 6530 _freelistLock->unlock(); 6531 ConcurrentMarkSweepThread::desynchronize(true); 6532 _collector->stopTimer(); 6533 if (PrintCMSStatistics != 0) { 6534 _collector->incrementYields(); 6535 } 6536 6537 // See the comment in coordinator_yield() 6538 for (unsigned i = 0; i < CMSYieldSleepCount && 6539 ConcurrentMarkSweepThread::should_yield() && 6540 !CMSCollector::foregroundGCIsActive(); ++i) { 6541 os::sleep(Thread::current(), 1, false); 6542 } 6543 6544 ConcurrentMarkSweepThread::synchronize(true); 6545 _freelistLock->lock_without_safepoint_check(); 6546 _bitMap->lock()->lock_without_safepoint_check(); 6547 _collector->startTimer(); 6548 } 6549 6550 6551 ////////////////////////////////////////////////////////////////// 6552 // SurvivorSpacePrecleanClosure 6553 ////////////////////////////////////////////////////////////////// 6554 // This (single-threaded) closure is used to preclean the oops in 6555 // the survivor spaces. 6556 size_t SurvivorSpacePrecleanClosure::do_object_careful(oop p) { 6557 6558 HeapWord* addr = (HeapWord*)p; 6559 DEBUG_ONLY(_collector->verify_work_stacks_empty();) 6560 assert(!_span.contains(addr), "we are scanning the survivor spaces"); 6561 assert(p->klass_or_null() != NULL, "object should be initialized"); 6562 // an initialized object; ignore mark word in verification below 6563 // since we are running concurrent with mutators 6564 assert(p->is_oop(true), "should be an oop"); 6565 // Note that we do not yield while we iterate over 6566 // the interior oops of p, pushing the relevant ones 6567 // on our marking stack. 6568 size_t size = p->oop_iterate(_scanning_closure); 6569 do_yield_check(); 6570 // Observe that below, we do not abandon the preclean 6571 // phase as soon as we should; rather we empty the 6572 // marking stack before returning. This is to satisfy 6573 // some existing assertions. In general, it may be a 6574 // good idea to abort immediately and complete the marking 6575 // from the grey objects at a later time. 6576 while (!_mark_stack->isEmpty()) { 6577 oop new_oop = _mark_stack->pop(); 6578 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop"); 6579 assert(_bit_map->isMarked((HeapWord*)new_oop), 6580 "only grey objects on this stack"); 6581 // iterate over the oops in this oop, marking and pushing 6582 // the ones in CMS heap (i.e. in _span). 6583 new_oop->oop_iterate(_scanning_closure); 6584 // check if it's time to yield 6585 do_yield_check(); 6586 } 6587 unsigned int after_count = 6588 GenCollectedHeap::heap()->total_collections(); 6589 bool abort = (_before_count != after_count) || 6590 _collector->should_abort_preclean(); 6591 return abort ? 0 : size; 6592 } 6593 6594 void SurvivorSpacePrecleanClosure::do_yield_work() { 6595 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 6596 "CMS thread should hold CMS token"); 6597 assert_lock_strong(_bit_map->lock()); 6598 // Relinquish the bit map lock 6599 _bit_map->lock()->unlock(); 6600 ConcurrentMarkSweepThread::desynchronize(true); 6601 _collector->stopTimer(); 6602 if (PrintCMSStatistics != 0) { 6603 _collector->incrementYields(); 6604 } 6605 6606 // See the comment in coordinator_yield() 6607 for (unsigned i = 0; i < CMSYieldSleepCount && 6608 ConcurrentMarkSweepThread::should_yield() && 6609 !CMSCollector::foregroundGCIsActive(); ++i) { 6610 os::sleep(Thread::current(), 1, false); 6611 } 6612 6613 ConcurrentMarkSweepThread::synchronize(true); 6614 _bit_map->lock()->lock_without_safepoint_check(); 6615 _collector->startTimer(); 6616 } 6617 6618 // This closure is used to rescan the marked objects on the dirty cards 6619 // in the mod union table and the card table proper. In the parallel 6620 // case, although the bitMap is shared, we do a single read so the 6621 // isMarked() query is "safe". 6622 bool ScanMarkedObjectsAgainClosure::do_object_bm(oop p, MemRegion mr) { 6623 // Ignore mark word because we are running concurrent with mutators 6624 assert(p->is_oop_or_null(true), err_msg("Expected an oop or NULL at " PTR_FORMAT, p2i(p))); 6625 HeapWord* addr = (HeapWord*)p; 6626 assert(_span.contains(addr), "we are scanning the CMS generation"); 6627 bool is_obj_array = false; 6628 #ifdef ASSERT 6629 if (!_parallel) { 6630 assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)"); 6631 assert(_collector->overflow_list_is_empty(), 6632 "overflow list should be empty"); 6633 6634 } 6635 #endif // ASSERT 6636 if (_bit_map->isMarked(addr)) { 6637 // Obj arrays are precisely marked, non-arrays are not; 6638 // so we scan objArrays precisely and non-arrays in their 6639 // entirety. 6640 if (p->is_objArray()) { 6641 is_obj_array = true; 6642 if (_parallel) { 6643 p->oop_iterate(_par_scan_closure, mr); 6644 } else { 6645 p->oop_iterate(_scan_closure, mr); 6646 } 6647 } else { 6648 if (_parallel) { 6649 p->oop_iterate(_par_scan_closure); 6650 } else { 6651 p->oop_iterate(_scan_closure); 6652 } 6653 } 6654 } 6655 #ifdef ASSERT 6656 if (!_parallel) { 6657 assert(_mark_stack->isEmpty(), "post-condition (eager drainage)"); 6658 assert(_collector->overflow_list_is_empty(), 6659 "overflow list should be empty"); 6660 6661 } 6662 #endif // ASSERT 6663 return is_obj_array; 6664 } 6665 6666 MarkFromRootsClosure::MarkFromRootsClosure(CMSCollector* collector, 6667 MemRegion span, 6668 CMSBitMap* bitMap, CMSMarkStack* markStack, 6669 bool should_yield, bool verifying): 6670 _collector(collector), 6671 _span(span), 6672 _bitMap(bitMap), 6673 _mut(&collector->_modUnionTable), 6674 _markStack(markStack), 6675 _yield(should_yield), 6676 _skipBits(0) 6677 { 6678 assert(_markStack->isEmpty(), "stack should be empty"); 6679 _finger = _bitMap->startWord(); 6680 _threshold = _finger; 6681 assert(_collector->_restart_addr == NULL, "Sanity check"); 6682 assert(_span.contains(_finger), "Out of bounds _finger?"); 6683 DEBUG_ONLY(_verifying = verifying;) 6684 } 6685 6686 void MarkFromRootsClosure::reset(HeapWord* addr) { 6687 assert(_markStack->isEmpty(), "would cause duplicates on stack"); 6688 assert(_span.contains(addr), "Out of bounds _finger?"); 6689 _finger = addr; 6690 _threshold = (HeapWord*)round_to( 6691 (intptr_t)_finger, CardTableModRefBS::card_size); 6692 } 6693 6694 // Should revisit to see if this should be restructured for 6695 // greater efficiency. 6696 bool MarkFromRootsClosure::do_bit(size_t offset) { 6697 if (_skipBits > 0) { 6698 _skipBits--; 6699 return true; 6700 } 6701 // convert offset into a HeapWord* 6702 HeapWord* addr = _bitMap->startWord() + offset; 6703 assert(_bitMap->endWord() && addr < _bitMap->endWord(), 6704 "address out of range"); 6705 assert(_bitMap->isMarked(addr), "tautology"); 6706 if (_bitMap->isMarked(addr+1)) { 6707 // this is an allocated but not yet initialized object 6708 assert(_skipBits == 0, "tautology"); 6709 _skipBits = 2; // skip next two marked bits ("Printezis-marks") 6710 oop p = oop(addr); 6711 if (p->klass_or_null() == NULL) { 6712 DEBUG_ONLY(if (!_verifying) {) 6713 // We re-dirty the cards on which this object lies and increase 6714 // the _threshold so that we'll come back to scan this object 6715 // during the preclean or remark phase. (CMSCleanOnEnter) 6716 if (CMSCleanOnEnter) { 6717 size_t sz = _collector->block_size_using_printezis_bits(addr); 6718 HeapWord* end_card_addr = (HeapWord*)round_to( 6719 (intptr_t)(addr+sz), CardTableModRefBS::card_size); 6720 MemRegion redirty_range = MemRegion(addr, end_card_addr); 6721 assert(!redirty_range.is_empty(), "Arithmetical tautology"); 6722 // Bump _threshold to end_card_addr; note that 6723 // _threshold cannot possibly exceed end_card_addr, anyhow. 6724 // This prevents future clearing of the card as the scan proceeds 6725 // to the right. 6726 assert(_threshold <= end_card_addr, 6727 "Because we are just scanning into this object"); 6728 if (_threshold < end_card_addr) { 6729 _threshold = end_card_addr; 6730 } 6731 if (p->klass_or_null() != NULL) { 6732 // Redirty the range of cards... 6733 _mut->mark_range(redirty_range); 6734 } // ...else the setting of klass will dirty the card anyway. 6735 } 6736 DEBUG_ONLY(}) 6737 return true; 6738 } 6739 } 6740 scanOopsInOop(addr); 6741 return true; 6742 } 6743 6744 // We take a break if we've been at this for a while, 6745 // so as to avoid monopolizing the locks involved. 6746 void MarkFromRootsClosure::do_yield_work() { 6747 // First give up the locks, then yield, then re-lock 6748 // We should probably use a constructor/destructor idiom to 6749 // do this unlock/lock or modify the MutexUnlocker class to 6750 // serve our purpose. XXX 6751 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 6752 "CMS thread should hold CMS token"); 6753 assert_lock_strong(_bitMap->lock()); 6754 _bitMap->lock()->unlock(); 6755 ConcurrentMarkSweepThread::desynchronize(true); 6756 _collector->stopTimer(); 6757 if (PrintCMSStatistics != 0) { 6758 _collector->incrementYields(); 6759 } 6760 6761 // See the comment in coordinator_yield() 6762 for (unsigned i = 0; i < CMSYieldSleepCount && 6763 ConcurrentMarkSweepThread::should_yield() && 6764 !CMSCollector::foregroundGCIsActive(); ++i) { 6765 os::sleep(Thread::current(), 1, false); 6766 } 6767 6768 ConcurrentMarkSweepThread::synchronize(true); 6769 _bitMap->lock()->lock_without_safepoint_check(); 6770 _collector->startTimer(); 6771 } 6772 6773 void MarkFromRootsClosure::scanOopsInOop(HeapWord* ptr) { 6774 assert(_bitMap->isMarked(ptr), "expected bit to be set"); 6775 assert(_markStack->isEmpty(), 6776 "should drain stack to limit stack usage"); 6777 // convert ptr to an oop preparatory to scanning 6778 oop obj = oop(ptr); 6779 // Ignore mark word in verification below, since we 6780 // may be running concurrent with mutators. 6781 assert(obj->is_oop(true), "should be an oop"); 6782 assert(_finger <= ptr, "_finger runneth ahead"); 6783 // advance the finger to right end of this object 6784 _finger = ptr + obj->size(); 6785 assert(_finger > ptr, "we just incremented it above"); 6786 // On large heaps, it may take us some time to get through 6787 // the marking phase. During 6788 // this time it's possible that a lot of mutations have 6789 // accumulated in the card table and the mod union table -- 6790 // these mutation records are redundant until we have 6791 // actually traced into the corresponding card. 6792 // Here, we check whether advancing the finger would make 6793 // us cross into a new card, and if so clear corresponding 6794 // cards in the MUT (preclean them in the card-table in the 6795 // future). 6796 6797 DEBUG_ONLY(if (!_verifying) {) 6798 // The clean-on-enter optimization is disabled by default, 6799 // until we fix 6178663. 6800 if (CMSCleanOnEnter && (_finger > _threshold)) { 6801 // [_threshold, _finger) represents the interval 6802 // of cards to be cleared in MUT (or precleaned in card table). 6803 // The set of cards to be cleared is all those that overlap 6804 // with the interval [_threshold, _finger); note that 6805 // _threshold is always kept card-aligned but _finger isn't 6806 // always card-aligned. 6807 HeapWord* old_threshold = _threshold; 6808 assert(old_threshold == (HeapWord*)round_to( 6809 (intptr_t)old_threshold, CardTableModRefBS::card_size), 6810 "_threshold should always be card-aligned"); 6811 _threshold = (HeapWord*)round_to( 6812 (intptr_t)_finger, CardTableModRefBS::card_size); 6813 MemRegion mr(old_threshold, _threshold); 6814 assert(!mr.is_empty(), "Control point invariant"); 6815 assert(_span.contains(mr), "Should clear within span"); 6816 _mut->clear_range(mr); 6817 } 6818 DEBUG_ONLY(}) 6819 // Note: the finger doesn't advance while we drain 6820 // the stack below. 6821 PushOrMarkClosure pushOrMarkClosure(_collector, 6822 _span, _bitMap, _markStack, 6823 _finger, this); 6824 bool res = _markStack->push(obj); 6825 assert(res, "Empty non-zero size stack should have space for single push"); 6826 while (!_markStack->isEmpty()) { 6827 oop new_oop = _markStack->pop(); 6828 // Skip verifying header mark word below because we are 6829 // running concurrent with mutators. 6830 assert(new_oop->is_oop(true), "Oops! expected to pop an oop"); 6831 // now scan this oop's oops 6832 new_oop->oop_iterate(&pushOrMarkClosure); 6833 do_yield_check(); 6834 } 6835 assert(_markStack->isEmpty(), "tautology, emphasizing post-condition"); 6836 } 6837 6838 Par_MarkFromRootsClosure::Par_MarkFromRootsClosure(CMSConcMarkingTask* task, 6839 CMSCollector* collector, MemRegion span, 6840 CMSBitMap* bit_map, 6841 OopTaskQueue* work_queue, 6842 CMSMarkStack* overflow_stack): 6843 _collector(collector), 6844 _whole_span(collector->_span), 6845 _span(span), 6846 _bit_map(bit_map), 6847 _mut(&collector->_modUnionTable), 6848 _work_queue(work_queue), 6849 _overflow_stack(overflow_stack), 6850 _skip_bits(0), 6851 _task(task) 6852 { 6853 assert(_work_queue->size() == 0, "work_queue should be empty"); 6854 _finger = span.start(); 6855 _threshold = _finger; // XXX Defer clear-on-enter optimization for now 6856 assert(_span.contains(_finger), "Out of bounds _finger?"); 6857 } 6858 6859 // Should revisit to see if this should be restructured for 6860 // greater efficiency. 6861 bool Par_MarkFromRootsClosure::do_bit(size_t offset) { 6862 if (_skip_bits > 0) { 6863 _skip_bits--; 6864 return true; 6865 } 6866 // convert offset into a HeapWord* 6867 HeapWord* addr = _bit_map->startWord() + offset; 6868 assert(_bit_map->endWord() && addr < _bit_map->endWord(), 6869 "address out of range"); 6870 assert(_bit_map->isMarked(addr), "tautology"); 6871 if (_bit_map->isMarked(addr+1)) { 6872 // this is an allocated object that might not yet be initialized 6873 assert(_skip_bits == 0, "tautology"); 6874 _skip_bits = 2; // skip next two marked bits ("Printezis-marks") 6875 oop p = oop(addr); 6876 if (p->klass_or_null() == NULL) { 6877 // in the case of Clean-on-Enter optimization, redirty card 6878 // and avoid clearing card by increasing the threshold. 6879 return true; 6880 } 6881 } 6882 scan_oops_in_oop(addr); 6883 return true; 6884 } 6885 6886 void Par_MarkFromRootsClosure::scan_oops_in_oop(HeapWord* ptr) { 6887 assert(_bit_map->isMarked(ptr), "expected bit to be set"); 6888 // Should we assert that our work queue is empty or 6889 // below some drain limit? 6890 assert(_work_queue->size() == 0, 6891 "should drain stack to limit stack usage"); 6892 // convert ptr to an oop preparatory to scanning 6893 oop obj = oop(ptr); 6894 // Ignore mark word in verification below, since we 6895 // may be running concurrent with mutators. 6896 assert(obj->is_oop(true), "should be an oop"); 6897 assert(_finger <= ptr, "_finger runneth ahead"); 6898 // advance the finger to right end of this object 6899 _finger = ptr + obj->size(); 6900 assert(_finger > ptr, "we just incremented it above"); 6901 // On large heaps, it may take us some time to get through 6902 // the marking phase. During 6903 // this time it's possible that a lot of mutations have 6904 // accumulated in the card table and the mod union table -- 6905 // these mutation records are redundant until we have 6906 // actually traced into the corresponding card. 6907 // Here, we check whether advancing the finger would make 6908 // us cross into a new card, and if so clear corresponding 6909 // cards in the MUT (preclean them in the card-table in the 6910 // future). 6911 6912 // The clean-on-enter optimization is disabled by default, 6913 // until we fix 6178663. 6914 if (CMSCleanOnEnter && (_finger > _threshold)) { 6915 // [_threshold, _finger) represents the interval 6916 // of cards to be cleared in MUT (or precleaned in card table). 6917 // The set of cards to be cleared is all those that overlap 6918 // with the interval [_threshold, _finger); note that 6919 // _threshold is always kept card-aligned but _finger isn't 6920 // always card-aligned. 6921 HeapWord* old_threshold = _threshold; 6922 assert(old_threshold == (HeapWord*)round_to( 6923 (intptr_t)old_threshold, CardTableModRefBS::card_size), 6924 "_threshold should always be card-aligned"); 6925 _threshold = (HeapWord*)round_to( 6926 (intptr_t)_finger, CardTableModRefBS::card_size); 6927 MemRegion mr(old_threshold, _threshold); 6928 assert(!mr.is_empty(), "Control point invariant"); 6929 assert(_span.contains(mr), "Should clear within span"); // _whole_span ?? 6930 _mut->clear_range(mr); 6931 } 6932 6933 // Note: the local finger doesn't advance while we drain 6934 // the stack below, but the global finger sure can and will. 6935 HeapWord** gfa = _task->global_finger_addr(); 6936 Par_PushOrMarkClosure pushOrMarkClosure(_collector, 6937 _span, _bit_map, 6938 _work_queue, 6939 _overflow_stack, 6940 _finger, 6941 gfa, this); 6942 bool res = _work_queue->push(obj); // overflow could occur here 6943 assert(res, "Will hold once we use workqueues"); 6944 while (true) { 6945 oop new_oop; 6946 if (!_work_queue->pop_local(new_oop)) { 6947 // We emptied our work_queue; check if there's stuff that can 6948 // be gotten from the overflow stack. 6949 if (CMSConcMarkingTask::get_work_from_overflow_stack( 6950 _overflow_stack, _work_queue)) { 6951 do_yield_check(); 6952 continue; 6953 } else { // done 6954 break; 6955 } 6956 } 6957 // Skip verifying header mark word below because we are 6958 // running concurrent with mutators. 6959 assert(new_oop->is_oop(true), "Oops! expected to pop an oop"); 6960 // now scan this oop's oops 6961 new_oop->oop_iterate(&pushOrMarkClosure); 6962 do_yield_check(); 6963 } 6964 assert(_work_queue->size() == 0, "tautology, emphasizing post-condition"); 6965 } 6966 6967 // Yield in response to a request from VM Thread or 6968 // from mutators. 6969 void Par_MarkFromRootsClosure::do_yield_work() { 6970 assert(_task != NULL, "sanity"); 6971 _task->yield(); 6972 } 6973 6974 // A variant of the above used for verifying CMS marking work. 6975 MarkFromRootsVerifyClosure::MarkFromRootsVerifyClosure(CMSCollector* collector, 6976 MemRegion span, 6977 CMSBitMap* verification_bm, CMSBitMap* cms_bm, 6978 CMSMarkStack* mark_stack): 6979 _collector(collector), 6980 _span(span), 6981 _verification_bm(verification_bm), 6982 _cms_bm(cms_bm), 6983 _mark_stack(mark_stack), 6984 _pam_verify_closure(collector, span, verification_bm, cms_bm, 6985 mark_stack) 6986 { 6987 assert(_mark_stack->isEmpty(), "stack should be empty"); 6988 _finger = _verification_bm->startWord(); 6989 assert(_collector->_restart_addr == NULL, "Sanity check"); 6990 assert(_span.contains(_finger), "Out of bounds _finger?"); 6991 } 6992 6993 void MarkFromRootsVerifyClosure::reset(HeapWord* addr) { 6994 assert(_mark_stack->isEmpty(), "would cause duplicates on stack"); 6995 assert(_span.contains(addr), "Out of bounds _finger?"); 6996 _finger = addr; 6997 } 6998 6999 // Should revisit to see if this should be restructured for 7000 // greater efficiency. 7001 bool MarkFromRootsVerifyClosure::do_bit(size_t offset) { 7002 // convert offset into a HeapWord* 7003 HeapWord* addr = _verification_bm->startWord() + offset; 7004 assert(_verification_bm->endWord() && addr < _verification_bm->endWord(), 7005 "address out of range"); 7006 assert(_verification_bm->isMarked(addr), "tautology"); 7007 assert(_cms_bm->isMarked(addr), "tautology"); 7008 7009 assert(_mark_stack->isEmpty(), 7010 "should drain stack to limit stack usage"); 7011 // convert addr to an oop preparatory to scanning 7012 oop obj = oop(addr); 7013 assert(obj->is_oop(), "should be an oop"); 7014 assert(_finger <= addr, "_finger runneth ahead"); 7015 // advance the finger to right end of this object 7016 _finger = addr + obj->size(); 7017 assert(_finger > addr, "we just incremented it above"); 7018 // Note: the finger doesn't advance while we drain 7019 // the stack below. 7020 bool res = _mark_stack->push(obj); 7021 assert(res, "Empty non-zero size stack should have space for single push"); 7022 while (!_mark_stack->isEmpty()) { 7023 oop new_oop = _mark_stack->pop(); 7024 assert(new_oop->is_oop(), "Oops! expected to pop an oop"); 7025 // now scan this oop's oops 7026 new_oop->oop_iterate(&_pam_verify_closure); 7027 } 7028 assert(_mark_stack->isEmpty(), "tautology, emphasizing post-condition"); 7029 return true; 7030 } 7031 7032 PushAndMarkVerifyClosure::PushAndMarkVerifyClosure( 7033 CMSCollector* collector, MemRegion span, 7034 CMSBitMap* verification_bm, CMSBitMap* cms_bm, 7035 CMSMarkStack* mark_stack): 7036 MetadataAwareOopClosure(collector->ref_processor()), 7037 _collector(collector), 7038 _span(span), 7039 _verification_bm(verification_bm), 7040 _cms_bm(cms_bm), 7041 _mark_stack(mark_stack) 7042 { } 7043 7044 void PushAndMarkVerifyClosure::do_oop(oop* p) { PushAndMarkVerifyClosure::do_oop_work(p); } 7045 void PushAndMarkVerifyClosure::do_oop(narrowOop* p) { PushAndMarkVerifyClosure::do_oop_work(p); } 7046 7047 // Upon stack overflow, we discard (part of) the stack, 7048 // remembering the least address amongst those discarded 7049 // in CMSCollector's _restart_address. 7050 void PushAndMarkVerifyClosure::handle_stack_overflow(HeapWord* lost) { 7051 // Remember the least grey address discarded 7052 HeapWord* ra = (HeapWord*)_mark_stack->least_value(lost); 7053 _collector->lower_restart_addr(ra); 7054 _mark_stack->reset(); // discard stack contents 7055 _mark_stack->expand(); // expand the stack if possible 7056 } 7057 7058 void PushAndMarkVerifyClosure::do_oop(oop obj) { 7059 assert(obj->is_oop_or_null(), err_msg("Expected an oop or NULL at " PTR_FORMAT, p2i(obj))); 7060 HeapWord* addr = (HeapWord*)obj; 7061 if (_span.contains(addr) && !_verification_bm->isMarked(addr)) { 7062 // Oop lies in _span and isn't yet grey or black 7063 _verification_bm->mark(addr); // now grey 7064 if (!_cms_bm->isMarked(addr)) { 7065 oop(addr)->print(); 7066 gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", 7067 addr); 7068 fatal("... aborting"); 7069 } 7070 7071 if (!_mark_stack->push(obj)) { // stack overflow 7072 if (PrintCMSStatistics != 0) { 7073 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at " 7074 SIZE_FORMAT, _mark_stack->capacity()); 7075 } 7076 assert(_mark_stack->isFull(), "Else push should have succeeded"); 7077 handle_stack_overflow(addr); 7078 } 7079 // anything including and to the right of _finger 7080 // will be scanned as we iterate over the remainder of the 7081 // bit map 7082 } 7083 } 7084 7085 PushOrMarkClosure::PushOrMarkClosure(CMSCollector* collector, 7086 MemRegion span, 7087 CMSBitMap* bitMap, CMSMarkStack* markStack, 7088 HeapWord* finger, MarkFromRootsClosure* parent) : 7089 MetadataAwareOopClosure(collector->ref_processor()), 7090 _collector(collector), 7091 _span(span), 7092 _bitMap(bitMap), 7093 _markStack(markStack), 7094 _finger(finger), 7095 _parent(parent) 7096 { } 7097 7098 Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector, 7099 MemRegion span, 7100 CMSBitMap* bit_map, 7101 OopTaskQueue* work_queue, 7102 CMSMarkStack* overflow_stack, 7103 HeapWord* finger, 7104 HeapWord** global_finger_addr, 7105 Par_MarkFromRootsClosure* parent) : 7106 MetadataAwareOopClosure(collector->ref_processor()), 7107 _collector(collector), 7108 _whole_span(collector->_span), 7109 _span(span), 7110 _bit_map(bit_map), 7111 _work_queue(work_queue), 7112 _overflow_stack(overflow_stack), 7113 _finger(finger), 7114 _global_finger_addr(global_finger_addr), 7115 _parent(parent) 7116 { } 7117 7118 // Assumes thread-safe access by callers, who are 7119 // responsible for mutual exclusion. 7120 void CMSCollector::lower_restart_addr(HeapWord* low) { 7121 assert(_span.contains(low), "Out of bounds addr"); 7122 if (_restart_addr == NULL) { 7123 _restart_addr = low; 7124 } else { 7125 _restart_addr = MIN2(_restart_addr, low); 7126 } 7127 } 7128 7129 // Upon stack overflow, we discard (part of) the stack, 7130 // remembering the least address amongst those discarded 7131 // in CMSCollector's _restart_address. 7132 void PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) { 7133 // Remember the least grey address discarded 7134 HeapWord* ra = (HeapWord*)_markStack->least_value(lost); 7135 _collector->lower_restart_addr(ra); 7136 _markStack->reset(); // discard stack contents 7137 _markStack->expand(); // expand the stack if possible 7138 } 7139 7140 // Upon stack overflow, we discard (part of) the stack, 7141 // remembering the least address amongst those discarded 7142 // in CMSCollector's _restart_address. 7143 void Par_PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) { 7144 // We need to do this under a mutex to prevent other 7145 // workers from interfering with the work done below. 7146 MutexLockerEx ml(_overflow_stack->par_lock(), 7147 Mutex::_no_safepoint_check_flag); 7148 // Remember the least grey address discarded 7149 HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost); 7150 _collector->lower_restart_addr(ra); 7151 _overflow_stack->reset(); // discard stack contents 7152 _overflow_stack->expand(); // expand the stack if possible 7153 } 7154 7155 void PushOrMarkClosure::do_oop(oop obj) { 7156 // Ignore mark word because we are running concurrent with mutators. 7157 assert(obj->is_oop_or_null(true), err_msg("Expected an oop or NULL at " PTR_FORMAT, p2i(obj))); 7158 HeapWord* addr = (HeapWord*)obj; 7159 if (_span.contains(addr) && !_bitMap->isMarked(addr)) { 7160 // Oop lies in _span and isn't yet grey or black 7161 _bitMap->mark(addr); // now grey 7162 if (addr < _finger) { 7163 // the bit map iteration has already either passed, or 7164 // sampled, this bit in the bit map; we'll need to 7165 // use the marking stack to scan this oop's oops. 7166 bool simulate_overflow = false; 7167 NOT_PRODUCT( 7168 if (CMSMarkStackOverflowALot && 7169 _collector->simulate_overflow()) { 7170 // simulate a stack overflow 7171 simulate_overflow = true; 7172 } 7173 ) 7174 if (simulate_overflow || !_markStack->push(obj)) { // stack overflow 7175 if (PrintCMSStatistics != 0) { 7176 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at " 7177 SIZE_FORMAT, _markStack->capacity()); 7178 } 7179 assert(simulate_overflow || _markStack->isFull(), "Else push should have succeeded"); 7180 handle_stack_overflow(addr); 7181 } 7182 } 7183 // anything including and to the right of _finger 7184 // will be scanned as we iterate over the remainder of the 7185 // bit map 7186 do_yield_check(); 7187 } 7188 } 7189 7190 void PushOrMarkClosure::do_oop(oop* p) { PushOrMarkClosure::do_oop_work(p); } 7191 void PushOrMarkClosure::do_oop(narrowOop* p) { PushOrMarkClosure::do_oop_work(p); } 7192 7193 void Par_PushOrMarkClosure::do_oop(oop obj) { 7194 // Ignore mark word because we are running concurrent with mutators. 7195 assert(obj->is_oop_or_null(true), err_msg("Expected an oop or NULL at " PTR_FORMAT, p2i(obj))); 7196 HeapWord* addr = (HeapWord*)obj; 7197 if (_whole_span.contains(addr) && !_bit_map->isMarked(addr)) { 7198 // Oop lies in _span and isn't yet grey or black 7199 // We read the global_finger (volatile read) strictly after marking oop 7200 bool res = _bit_map->par_mark(addr); // now grey 7201 volatile HeapWord** gfa = (volatile HeapWord**)_global_finger_addr; 7202 // Should we push this marked oop on our stack? 7203 // -- if someone else marked it, nothing to do 7204 // -- if target oop is above global finger nothing to do 7205 // -- if target oop is in chunk and above local finger 7206 // then nothing to do 7207 // -- else push on work queue 7208 if ( !res // someone else marked it, they will deal with it 7209 || (addr >= *gfa) // will be scanned in a later task 7210 || (_span.contains(addr) && addr >= _finger)) { // later in this chunk 7211 return; 7212 } 7213 // the bit map iteration has already either passed, or 7214 // sampled, this bit in the bit map; we'll need to 7215 // use the marking stack to scan this oop's oops. 7216 bool simulate_overflow = false; 7217 NOT_PRODUCT( 7218 if (CMSMarkStackOverflowALot && 7219 _collector->simulate_overflow()) { 7220 // simulate a stack overflow 7221 simulate_overflow = true; 7222 } 7223 ) 7224 if (simulate_overflow || 7225 !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) { 7226 // stack overflow 7227 if (PrintCMSStatistics != 0) { 7228 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at " 7229 SIZE_FORMAT, _overflow_stack->capacity()); 7230 } 7231 // We cannot assert that the overflow stack is full because 7232 // it may have been emptied since. 7233 assert(simulate_overflow || 7234 _work_queue->size() == _work_queue->max_elems(), 7235 "Else push should have succeeded"); 7236 handle_stack_overflow(addr); 7237 } 7238 do_yield_check(); 7239 } 7240 } 7241 7242 void Par_PushOrMarkClosure::do_oop(oop* p) { Par_PushOrMarkClosure::do_oop_work(p); } 7243 void Par_PushOrMarkClosure::do_oop(narrowOop* p) { Par_PushOrMarkClosure::do_oop_work(p); } 7244 7245 PushAndMarkClosure::PushAndMarkClosure(CMSCollector* collector, 7246 MemRegion span, 7247 ReferenceProcessor* rp, 7248 CMSBitMap* bit_map, 7249 CMSBitMap* mod_union_table, 7250 CMSMarkStack* mark_stack, 7251 bool concurrent_precleaning): 7252 MetadataAwareOopClosure(rp), 7253 _collector(collector), 7254 _span(span), 7255 _bit_map(bit_map), 7256 _mod_union_table(mod_union_table), 7257 _mark_stack(mark_stack), 7258 _concurrent_precleaning(concurrent_precleaning) 7259 { 7260 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 7261 } 7262 7263 // Grey object rescan during pre-cleaning and second checkpoint phases -- 7264 // the non-parallel version (the parallel version appears further below.) 7265 void PushAndMarkClosure::do_oop(oop obj) { 7266 // Ignore mark word verification. If during concurrent precleaning, 7267 // the object monitor may be locked. If during the checkpoint 7268 // phases, the object may already have been reached by a different 7269 // path and may be at the end of the global overflow list (so 7270 // the mark word may be NULL). 7271 assert(obj->is_oop_or_null(true /* ignore mark word */), 7272 err_msg("Expected an oop or NULL at " PTR_FORMAT, p2i(obj))); 7273 HeapWord* addr = (HeapWord*)obj; 7274 // Check if oop points into the CMS generation 7275 // and is not marked 7276 if (_span.contains(addr) && !_bit_map->isMarked(addr)) { 7277 // a white object ... 7278 _bit_map->mark(addr); // ... now grey 7279 // push on the marking stack (grey set) 7280 bool simulate_overflow = false; 7281 NOT_PRODUCT( 7282 if (CMSMarkStackOverflowALot && 7283 _collector->simulate_overflow()) { 7284 // simulate a stack overflow 7285 simulate_overflow = true; 7286 } 7287 ) 7288 if (simulate_overflow || !_mark_stack->push(obj)) { 7289 if (_concurrent_precleaning) { 7290 // During precleaning we can just dirty the appropriate card(s) 7291 // in the mod union table, thus ensuring that the object remains 7292 // in the grey set and continue. In the case of object arrays 7293 // we need to dirty all of the cards that the object spans, 7294 // since the rescan of object arrays will be limited to the 7295 // dirty cards. 7296 // Note that no one can be interfering with us in this action 7297 // of dirtying the mod union table, so no locking or atomics 7298 // are required. 7299 if (obj->is_objArray()) { 7300 size_t sz = obj->size(); 7301 HeapWord* end_card_addr = (HeapWord*)round_to( 7302 (intptr_t)(addr+sz), CardTableModRefBS::card_size); 7303 MemRegion redirty_range = MemRegion(addr, end_card_addr); 7304 assert(!redirty_range.is_empty(), "Arithmetical tautology"); 7305 _mod_union_table->mark_range(redirty_range); 7306 } else { 7307 _mod_union_table->mark(addr); 7308 } 7309 _collector->_ser_pmc_preclean_ovflw++; 7310 } else { 7311 // During the remark phase, we need to remember this oop 7312 // in the overflow list. 7313 _collector->push_on_overflow_list(obj); 7314 _collector->_ser_pmc_remark_ovflw++; 7315 } 7316 } 7317 } 7318 } 7319 7320 Par_PushAndMarkClosure::Par_PushAndMarkClosure(CMSCollector* collector, 7321 MemRegion span, 7322 ReferenceProcessor* rp, 7323 CMSBitMap* bit_map, 7324 OopTaskQueue* work_queue): 7325 MetadataAwareOopClosure(rp), 7326 _collector(collector), 7327 _span(span), 7328 _bit_map(bit_map), 7329 _work_queue(work_queue) 7330 { 7331 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 7332 } 7333 7334 void PushAndMarkClosure::do_oop(oop* p) { PushAndMarkClosure::do_oop_work(p); } 7335 void PushAndMarkClosure::do_oop(narrowOop* p) { PushAndMarkClosure::do_oop_work(p); } 7336 7337 // Grey object rescan during second checkpoint phase -- 7338 // the parallel version. 7339 void Par_PushAndMarkClosure::do_oop(oop obj) { 7340 // In the assert below, we ignore the mark word because 7341 // this oop may point to an already visited object that is 7342 // on the overflow stack (in which case the mark word has 7343 // been hijacked for chaining into the overflow stack -- 7344 // if this is the last object in the overflow stack then 7345 // its mark word will be NULL). Because this object may 7346 // have been subsequently popped off the global overflow 7347 // stack, and the mark word possibly restored to the prototypical 7348 // value, by the time we get to examined this failing assert in 7349 // the debugger, is_oop_or_null(false) may subsequently start 7350 // to hold. 7351 assert(obj->is_oop_or_null(true), 7352 err_msg("Expected an oop or NULL at " PTR_FORMAT, p2i(obj))); 7353 HeapWord* addr = (HeapWord*)obj; 7354 // Check if oop points into the CMS generation 7355 // and is not marked 7356 if (_span.contains(addr) && !_bit_map->isMarked(addr)) { 7357 // a white object ... 7358 // If we manage to "claim" the object, by being the 7359 // first thread to mark it, then we push it on our 7360 // marking stack 7361 if (_bit_map->par_mark(addr)) { // ... now grey 7362 // push on work queue (grey set) 7363 bool simulate_overflow = false; 7364 NOT_PRODUCT( 7365 if (CMSMarkStackOverflowALot && 7366 _collector->par_simulate_overflow()) { 7367 // simulate a stack overflow 7368 simulate_overflow = true; 7369 } 7370 ) 7371 if (simulate_overflow || !_work_queue->push(obj)) { 7372 _collector->par_push_on_overflow_list(obj); 7373 _collector->_par_pmc_remark_ovflw++; // imprecise OK: no need to CAS 7374 } 7375 } // Else, some other thread got there first 7376 } 7377 } 7378 7379 void Par_PushAndMarkClosure::do_oop(oop* p) { Par_PushAndMarkClosure::do_oop_work(p); } 7380 void Par_PushAndMarkClosure::do_oop(narrowOop* p) { Par_PushAndMarkClosure::do_oop_work(p); } 7381 7382 void CMSPrecleanRefsYieldClosure::do_yield_work() { 7383 Mutex* bml = _collector->bitMapLock(); 7384 assert_lock_strong(bml); 7385 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 7386 "CMS thread should hold CMS token"); 7387 7388 bml->unlock(); 7389 ConcurrentMarkSweepThread::desynchronize(true); 7390 7391 _collector->stopTimer(); 7392 if (PrintCMSStatistics != 0) { 7393 _collector->incrementYields(); 7394 } 7395 7396 // See the comment in coordinator_yield() 7397 for (unsigned i = 0; i < CMSYieldSleepCount && 7398 ConcurrentMarkSweepThread::should_yield() && 7399 !CMSCollector::foregroundGCIsActive(); ++i) { 7400 os::sleep(Thread::current(), 1, false); 7401 } 7402 7403 ConcurrentMarkSweepThread::synchronize(true); 7404 bml->lock(); 7405 7406 _collector->startTimer(); 7407 } 7408 7409 bool CMSPrecleanRefsYieldClosure::should_return() { 7410 if (ConcurrentMarkSweepThread::should_yield()) { 7411 do_yield_work(); 7412 } 7413 return _collector->foregroundGCIsActive(); 7414 } 7415 7416 void MarkFromDirtyCardsClosure::do_MemRegion(MemRegion mr) { 7417 assert(((size_t)mr.start())%CardTableModRefBS::card_size_in_words == 0, 7418 "mr should be aligned to start at a card boundary"); 7419 // We'd like to assert: 7420 // assert(mr.word_size()%CardTableModRefBS::card_size_in_words == 0, 7421 // "mr should be a range of cards"); 7422 // However, that would be too strong in one case -- the last 7423 // partition ends at _unallocated_block which, in general, can be 7424 // an arbitrary boundary, not necessarily card aligned. 7425 if (PrintCMSStatistics != 0) { 7426 _num_dirty_cards += 7427 mr.word_size()/CardTableModRefBS::card_size_in_words; 7428 } 7429 _space->object_iterate_mem(mr, &_scan_cl); 7430 } 7431 7432 SweepClosure::SweepClosure(CMSCollector* collector, 7433 ConcurrentMarkSweepGeneration* g, 7434 CMSBitMap* bitMap, bool should_yield) : 7435 _collector(collector), 7436 _g(g), 7437 _sp(g->cmsSpace()), 7438 _limit(_sp->sweep_limit()), 7439 _freelistLock(_sp->freelistLock()), 7440 _bitMap(bitMap), 7441 _yield(should_yield), 7442 _inFreeRange(false), // No free range at beginning of sweep 7443 _freeRangeInFreeLists(false), // No free range at beginning of sweep 7444 _lastFreeRangeCoalesced(false), 7445 _freeFinger(g->used_region().start()) 7446 { 7447 NOT_PRODUCT( 7448 _numObjectsFreed = 0; 7449 _numWordsFreed = 0; 7450 _numObjectsLive = 0; 7451 _numWordsLive = 0; 7452 _numObjectsAlreadyFree = 0; 7453 _numWordsAlreadyFree = 0; 7454 _last_fc = NULL; 7455 7456 _sp->initializeIndexedFreeListArrayReturnedBytes(); 7457 _sp->dictionary()->initialize_dict_returned_bytes(); 7458 ) 7459 assert(_limit >= _sp->bottom() && _limit <= _sp->end(), 7460 "sweep _limit out of bounds"); 7461 if (CMSTraceSweeper) { 7462 gclog_or_tty->print_cr("\n====================\nStarting new sweep with limit " PTR_FORMAT, 7463 _limit); 7464 } 7465 } 7466 7467 void SweepClosure::print_on(outputStream* st) const { 7468 tty->print_cr("_sp = [" PTR_FORMAT "," PTR_FORMAT ")", 7469 _sp->bottom(), _sp->end()); 7470 tty->print_cr("_limit = " PTR_FORMAT, _limit); 7471 tty->print_cr("_freeFinger = " PTR_FORMAT, _freeFinger); 7472 NOT_PRODUCT(tty->print_cr("_last_fc = " PTR_FORMAT, _last_fc);) 7473 tty->print_cr("_inFreeRange = %d, _freeRangeInFreeLists = %d, _lastFreeRangeCoalesced = %d", 7474 _inFreeRange, _freeRangeInFreeLists, _lastFreeRangeCoalesced); 7475 } 7476 7477 #ifndef PRODUCT 7478 // Assertion checking only: no useful work in product mode -- 7479 // however, if any of the flags below become product flags, 7480 // you may need to review this code to see if it needs to be 7481 // enabled in product mode. 7482 SweepClosure::~SweepClosure() { 7483 assert_lock_strong(_freelistLock); 7484 assert(_limit >= _sp->bottom() && _limit <= _sp->end(), 7485 "sweep _limit out of bounds"); 7486 if (inFreeRange()) { 7487 warning("inFreeRange() should have been reset; dumping state of SweepClosure"); 7488 print(); 7489 ShouldNotReachHere(); 7490 } 7491 if (Verbose && PrintGC) { 7492 gclog_or_tty->print("Collected "SIZE_FORMAT" objects, " SIZE_FORMAT " bytes", 7493 _numObjectsFreed, _numWordsFreed*sizeof(HeapWord)); 7494 gclog_or_tty->print_cr("\nLive "SIZE_FORMAT" objects, " 7495 SIZE_FORMAT" bytes " 7496 "Already free "SIZE_FORMAT" objects, "SIZE_FORMAT" bytes", 7497 _numObjectsLive, _numWordsLive*sizeof(HeapWord), 7498 _numObjectsAlreadyFree, _numWordsAlreadyFree*sizeof(HeapWord)); 7499 size_t totalBytes = (_numWordsFreed + _numWordsLive + _numWordsAlreadyFree) 7500 * sizeof(HeapWord); 7501 gclog_or_tty->print_cr("Total sweep: "SIZE_FORMAT" bytes", totalBytes); 7502 7503 if (PrintCMSStatistics && CMSVerifyReturnedBytes) { 7504 size_t indexListReturnedBytes = _sp->sumIndexedFreeListArrayReturnedBytes(); 7505 size_t dict_returned_bytes = _sp->dictionary()->sum_dict_returned_bytes(); 7506 size_t returned_bytes = indexListReturnedBytes + dict_returned_bytes; 7507 gclog_or_tty->print("Returned "SIZE_FORMAT" bytes", returned_bytes); 7508 gclog_or_tty->print(" Indexed List Returned "SIZE_FORMAT" bytes", 7509 indexListReturnedBytes); 7510 gclog_or_tty->print_cr(" Dictionary Returned "SIZE_FORMAT" bytes", 7511 dict_returned_bytes); 7512 } 7513 } 7514 if (CMSTraceSweeper) { 7515 gclog_or_tty->print_cr("end of sweep with _limit = " PTR_FORMAT "\n================", 7516 _limit); 7517 } 7518 } 7519 #endif // PRODUCT 7520 7521 void SweepClosure::initialize_free_range(HeapWord* freeFinger, 7522 bool freeRangeInFreeLists) { 7523 if (CMSTraceSweeper) { 7524 gclog_or_tty->print("---- Start free range at " PTR_FORMAT " with free block (%d)\n", 7525 freeFinger, freeRangeInFreeLists); 7526 } 7527 assert(!inFreeRange(), "Trampling existing free range"); 7528 set_inFreeRange(true); 7529 set_lastFreeRangeCoalesced(false); 7530 7531 set_freeFinger(freeFinger); 7532 set_freeRangeInFreeLists(freeRangeInFreeLists); 7533 if (CMSTestInFreeList) { 7534 if (freeRangeInFreeLists) { 7535 FreeChunk* fc = (FreeChunk*) freeFinger; 7536 assert(fc->is_free(), "A chunk on the free list should be free."); 7537 assert(fc->size() > 0, "Free range should have a size"); 7538 assert(_sp->verify_chunk_in_free_list(fc), "Chunk is not in free lists"); 7539 } 7540 } 7541 } 7542 7543 // Note that the sweeper runs concurrently with mutators. Thus, 7544 // it is possible for direct allocation in this generation to happen 7545 // in the middle of the sweep. Note that the sweeper also coalesces 7546 // contiguous free blocks. Thus, unless the sweeper and the allocator 7547 // synchronize appropriately freshly allocated blocks may get swept up. 7548 // This is accomplished by the sweeper locking the free lists while 7549 // it is sweeping. Thus blocks that are determined to be free are 7550 // indeed free. There is however one additional complication: 7551 // blocks that have been allocated since the final checkpoint and 7552 // mark, will not have been marked and so would be treated as 7553 // unreachable and swept up. To prevent this, the allocator marks 7554 // the bit map when allocating during the sweep phase. This leads, 7555 // however, to a further complication -- objects may have been allocated 7556 // but not yet initialized -- in the sense that the header isn't yet 7557 // installed. The sweeper can not then determine the size of the block 7558 // in order to skip over it. To deal with this case, we use a technique 7559 // (due to Printezis) to encode such uninitialized block sizes in the 7560 // bit map. Since the bit map uses a bit per every HeapWord, but the 7561 // CMS generation has a minimum object size of 3 HeapWords, it follows 7562 // that "normal marks" won't be adjacent in the bit map (there will 7563 // always be at least two 0 bits between successive 1 bits). We make use 7564 // of these "unused" bits to represent uninitialized blocks -- the bit 7565 // corresponding to the start of the uninitialized object and the next 7566 // bit are both set. Finally, a 1 bit marks the end of the object that 7567 // started with the two consecutive 1 bits to indicate its potentially 7568 // uninitialized state. 7569 7570 size_t SweepClosure::do_blk_careful(HeapWord* addr) { 7571 FreeChunk* fc = (FreeChunk*)addr; 7572 size_t res; 7573 7574 // Check if we are done sweeping. Below we check "addr >= _limit" rather 7575 // than "addr == _limit" because although _limit was a block boundary when 7576 // we started the sweep, it may no longer be one because heap expansion 7577 // may have caused us to coalesce the block ending at the address _limit 7578 // with a newly expanded chunk (this happens when _limit was set to the 7579 // previous _end of the space), so we may have stepped past _limit: 7580 // see the following Zeno-like trail of CRs 6977970, 7008136, 7042740. 7581 if (addr >= _limit) { // we have swept up to or past the limit: finish up 7582 assert(_limit >= _sp->bottom() && _limit <= _sp->end(), 7583 "sweep _limit out of bounds"); 7584 assert(addr < _sp->end(), "addr out of bounds"); 7585 // Flush any free range we might be holding as a single 7586 // coalesced chunk to the appropriate free list. 7587 if (inFreeRange()) { 7588 assert(freeFinger() >= _sp->bottom() && freeFinger() < _limit, 7589 err_msg("freeFinger() " PTR_FORMAT" is out-of-bounds", freeFinger())); 7590 flush_cur_free_chunk(freeFinger(), 7591 pointer_delta(addr, freeFinger())); 7592 if (CMSTraceSweeper) { 7593 gclog_or_tty->print("Sweep: last chunk: "); 7594 gclog_or_tty->print("put_free_blk " PTR_FORMAT " ("SIZE_FORMAT") " 7595 "[coalesced:%d]\n", 7596 freeFinger(), pointer_delta(addr, freeFinger()), 7597 lastFreeRangeCoalesced() ? 1 : 0); 7598 } 7599 } 7600 7601 // help the iterator loop finish 7602 return pointer_delta(_sp->end(), addr); 7603 } 7604 7605 assert(addr < _limit, "sweep invariant"); 7606 // check if we should yield 7607 do_yield_check(addr); 7608 if (fc->is_free()) { 7609 // Chunk that is already free 7610 res = fc->size(); 7611 do_already_free_chunk(fc); 7612 debug_only(_sp->verifyFreeLists()); 7613 // If we flush the chunk at hand in lookahead_and_flush() 7614 // and it's coalesced with a preceding chunk, then the 7615 // process of "mangling" the payload of the coalesced block 7616 // will cause erasure of the size information from the 7617 // (erstwhile) header of all the coalesced blocks but the 7618 // first, so the first disjunct in the assert will not hold 7619 // in that specific case (in which case the second disjunct 7620 // will hold). 7621 assert(res == fc->size() || ((HeapWord*)fc) + res >= _limit, 7622 "Otherwise the size info doesn't change at this step"); 7623 NOT_PRODUCT( 7624 _numObjectsAlreadyFree++; 7625 _numWordsAlreadyFree += res; 7626 ) 7627 NOT_PRODUCT(_last_fc = fc;) 7628 } else if (!_bitMap->isMarked(addr)) { 7629 // Chunk is fresh garbage 7630 res = do_garbage_chunk(fc); 7631 debug_only(_sp->verifyFreeLists()); 7632 NOT_PRODUCT( 7633 _numObjectsFreed++; 7634 _numWordsFreed += res; 7635 ) 7636 } else { 7637 // Chunk that is alive. 7638 res = do_live_chunk(fc); 7639 debug_only(_sp->verifyFreeLists()); 7640 NOT_PRODUCT( 7641 _numObjectsLive++; 7642 _numWordsLive += res; 7643 ) 7644 } 7645 return res; 7646 } 7647 7648 // For the smart allocation, record following 7649 // split deaths - a free chunk is removed from its free list because 7650 // it is being split into two or more chunks. 7651 // split birth - a free chunk is being added to its free list because 7652 // a larger free chunk has been split and resulted in this free chunk. 7653 // coal death - a free chunk is being removed from its free list because 7654 // it is being coalesced into a large free chunk. 7655 // coal birth - a free chunk is being added to its free list because 7656 // it was created when two or more free chunks where coalesced into 7657 // this free chunk. 7658 // 7659 // These statistics are used to determine the desired number of free 7660 // chunks of a given size. The desired number is chosen to be relative 7661 // to the end of a CMS sweep. The desired number at the end of a sweep 7662 // is the 7663 // count-at-end-of-previous-sweep (an amount that was enough) 7664 // - count-at-beginning-of-current-sweep (the excess) 7665 // + split-births (gains in this size during interval) 7666 // - split-deaths (demands on this size during interval) 7667 // where the interval is from the end of one sweep to the end of the 7668 // next. 7669 // 7670 // When sweeping the sweeper maintains an accumulated chunk which is 7671 // the chunk that is made up of chunks that have been coalesced. That 7672 // will be termed the left-hand chunk. A new chunk of garbage that 7673 // is being considered for coalescing will be referred to as the 7674 // right-hand chunk. 7675 // 7676 // When making a decision on whether to coalesce a right-hand chunk with 7677 // the current left-hand chunk, the current count vs. the desired count 7678 // of the left-hand chunk is considered. Also if the right-hand chunk 7679 // is near the large chunk at the end of the heap (see 7680 // ConcurrentMarkSweepGeneration::isNearLargestChunk()), then the 7681 // left-hand chunk is coalesced. 7682 // 7683 // When making a decision about whether to split a chunk, the desired count 7684 // vs. the current count of the candidate to be split is also considered. 7685 // If the candidate is underpopulated (currently fewer chunks than desired) 7686 // a chunk of an overpopulated (currently more chunks than desired) size may 7687 // be chosen. The "hint" associated with a free list, if non-null, points 7688 // to a free list which may be overpopulated. 7689 // 7690 7691 void SweepClosure::do_already_free_chunk(FreeChunk* fc) { 7692 const size_t size = fc->size(); 7693 // Chunks that cannot be coalesced are not in the 7694 // free lists. 7695 if (CMSTestInFreeList && !fc->cantCoalesce()) { 7696 assert(_sp->verify_chunk_in_free_list(fc), 7697 "free chunk should be in free lists"); 7698 } 7699 // a chunk that is already free, should not have been 7700 // marked in the bit map 7701 HeapWord* const addr = (HeapWord*) fc; 7702 assert(!_bitMap->isMarked(addr), "free chunk should be unmarked"); 7703 // Verify that the bit map has no bits marked between 7704 // addr and purported end of this block. 7705 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size); 7706 7707 // Some chunks cannot be coalesced under any circumstances. 7708 // See the definition of cantCoalesce(). 7709 if (!fc->cantCoalesce()) { 7710 // This chunk can potentially be coalesced. 7711 if (_sp->adaptive_freelists()) { 7712 // All the work is done in 7713 do_post_free_or_garbage_chunk(fc, size); 7714 } else { // Not adaptive free lists 7715 // this is a free chunk that can potentially be coalesced by the sweeper; 7716 if (!inFreeRange()) { 7717 // if the next chunk is a free block that can't be coalesced 7718 // it doesn't make sense to remove this chunk from the free lists 7719 FreeChunk* nextChunk = (FreeChunk*)(addr + size); 7720 assert((HeapWord*)nextChunk <= _sp->end(), "Chunk size out of bounds?"); 7721 if ((HeapWord*)nextChunk < _sp->end() && // There is another free chunk to the right ... 7722 nextChunk->is_free() && // ... which is free... 7723 nextChunk->cantCoalesce()) { // ... but can't be coalesced 7724 // nothing to do 7725 } else { 7726 // Potentially the start of a new free range: 7727 // Don't eagerly remove it from the free lists. 7728 // No need to remove it if it will just be put 7729 // back again. (Also from a pragmatic point of view 7730 // if it is a free block in a region that is beyond 7731 // any allocated blocks, an assertion will fail) 7732 // Remember the start of a free run. 7733 initialize_free_range(addr, true); 7734 // end - can coalesce with next chunk 7735 } 7736 } else { 7737 // the midst of a free range, we are coalescing 7738 print_free_block_coalesced(fc); 7739 if (CMSTraceSweeper) { 7740 gclog_or_tty->print(" -- pick up free block " PTR_FORMAT " (" SIZE_FORMAT ")\n", fc, size); 7741 } 7742 // remove it from the free lists 7743 _sp->removeFreeChunkFromFreeLists(fc); 7744 set_lastFreeRangeCoalesced(true); 7745 // If the chunk is being coalesced and the current free range is 7746 // in the free lists, remove the current free range so that it 7747 // will be returned to the free lists in its entirety - all 7748 // the coalesced pieces included. 7749 if (freeRangeInFreeLists()) { 7750 FreeChunk* ffc = (FreeChunk*) freeFinger(); 7751 assert(ffc->size() == pointer_delta(addr, freeFinger()), 7752 "Size of free range is inconsistent with chunk size."); 7753 if (CMSTestInFreeList) { 7754 assert(_sp->verify_chunk_in_free_list(ffc), 7755 "free range is not in free lists"); 7756 } 7757 _sp->removeFreeChunkFromFreeLists(ffc); 7758 set_freeRangeInFreeLists(false); 7759 } 7760 } 7761 } 7762 // Note that if the chunk is not coalescable (the else arm 7763 // below), we unconditionally flush, without needing to do 7764 // a "lookahead," as we do below. 7765 if (inFreeRange()) lookahead_and_flush(fc, size); 7766 } else { 7767 // Code path common to both original and adaptive free lists. 7768 7769 // cant coalesce with previous block; this should be treated 7770 // as the end of a free run if any 7771 if (inFreeRange()) { 7772 // we kicked some butt; time to pick up the garbage 7773 assert(freeFinger() < addr, "freeFinger points too high"); 7774 flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger())); 7775 } 7776 // else, nothing to do, just continue 7777 } 7778 } 7779 7780 size_t SweepClosure::do_garbage_chunk(FreeChunk* fc) { 7781 // This is a chunk of garbage. It is not in any free list. 7782 // Add it to a free list or let it possibly be coalesced into 7783 // a larger chunk. 7784 HeapWord* const addr = (HeapWord*) fc; 7785 const size_t size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()); 7786 7787 if (_sp->adaptive_freelists()) { 7788 // Verify that the bit map has no bits marked between 7789 // addr and purported end of just dead object. 7790 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size); 7791 7792 do_post_free_or_garbage_chunk(fc, size); 7793 } else { 7794 if (!inFreeRange()) { 7795 // start of a new free range 7796 assert(size > 0, "A free range should have a size"); 7797 initialize_free_range(addr, false); 7798 } else { 7799 // this will be swept up when we hit the end of the 7800 // free range 7801 if (CMSTraceSweeper) { 7802 gclog_or_tty->print(" -- pick up garbage " PTR_FORMAT " (" SIZE_FORMAT ")\n", fc, size); 7803 } 7804 // If the chunk is being coalesced and the current free range is 7805 // in the free lists, remove the current free range so that it 7806 // will be returned to the free lists in its entirety - all 7807 // the coalesced pieces included. 7808 if (freeRangeInFreeLists()) { 7809 FreeChunk* ffc = (FreeChunk*)freeFinger(); 7810 assert(ffc->size() == pointer_delta(addr, freeFinger()), 7811 "Size of free range is inconsistent with chunk size."); 7812 if (CMSTestInFreeList) { 7813 assert(_sp->verify_chunk_in_free_list(ffc), 7814 "free range is not in free lists"); 7815 } 7816 _sp->removeFreeChunkFromFreeLists(ffc); 7817 set_freeRangeInFreeLists(false); 7818 } 7819 set_lastFreeRangeCoalesced(true); 7820 } 7821 // this will be swept up when we hit the end of the free range 7822 7823 // Verify that the bit map has no bits marked between 7824 // addr and purported end of just dead object. 7825 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size); 7826 } 7827 assert(_limit >= addr + size, 7828 "A freshly garbage chunk can't possibly straddle over _limit"); 7829 if (inFreeRange()) lookahead_and_flush(fc, size); 7830 return size; 7831 } 7832 7833 size_t SweepClosure::do_live_chunk(FreeChunk* fc) { 7834 HeapWord* addr = (HeapWord*) fc; 7835 // The sweeper has just found a live object. Return any accumulated 7836 // left hand chunk to the free lists. 7837 if (inFreeRange()) { 7838 assert(freeFinger() < addr, "freeFinger points too high"); 7839 flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger())); 7840 } 7841 7842 // This object is live: we'd normally expect this to be 7843 // an oop, and like to assert the following: 7844 // assert(oop(addr)->is_oop(), "live block should be an oop"); 7845 // However, as we commented above, this may be an object whose 7846 // header hasn't yet been initialized. 7847 size_t size; 7848 assert(_bitMap->isMarked(addr), "Tautology for this control point"); 7849 if (_bitMap->isMarked(addr + 1)) { 7850 // Determine the size from the bit map, rather than trying to 7851 // compute it from the object header. 7852 HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2); 7853 size = pointer_delta(nextOneAddr + 1, addr); 7854 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 7855 "alignment problem"); 7856 7857 #ifdef ASSERT 7858 if (oop(addr)->klass_or_null() != NULL) { 7859 // Ignore mark word because we are running concurrent with mutators 7860 assert(oop(addr)->is_oop(true), "live block should be an oop"); 7861 assert(size == 7862 CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()), 7863 "P-mark and computed size do not agree"); 7864 } 7865 #endif 7866 7867 } else { 7868 // This should be an initialized object that's alive. 7869 assert(oop(addr)->klass_or_null() != NULL, 7870 "Should be an initialized object"); 7871 // Ignore mark word because we are running concurrent with mutators 7872 assert(oop(addr)->is_oop(true), "live block should be an oop"); 7873 // Verify that the bit map has no bits marked between 7874 // addr and purported end of this block. 7875 size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()); 7876 assert(size >= 3, "Necessary for Printezis marks to work"); 7877 assert(!_bitMap->isMarked(addr+1), "Tautology for this control point"); 7878 DEBUG_ONLY(_bitMap->verifyNoOneBitsInRange(addr+2, addr+size);) 7879 } 7880 return size; 7881 } 7882 7883 void SweepClosure::do_post_free_or_garbage_chunk(FreeChunk* fc, 7884 size_t chunkSize) { 7885 // do_post_free_or_garbage_chunk() should only be called in the case 7886 // of the adaptive free list allocator. 7887 const bool fcInFreeLists = fc->is_free(); 7888 assert(_sp->adaptive_freelists(), "Should only be used in this case."); 7889 assert((HeapWord*)fc <= _limit, "sweep invariant"); 7890 if (CMSTestInFreeList && fcInFreeLists) { 7891 assert(_sp->verify_chunk_in_free_list(fc), "free chunk is not in free lists"); 7892 } 7893 7894 if (CMSTraceSweeper) { 7895 gclog_or_tty->print_cr(" -- pick up another chunk at " PTR_FORMAT " (" SIZE_FORMAT ")", fc, chunkSize); 7896 } 7897 7898 HeapWord* const fc_addr = (HeapWord*) fc; 7899 7900 bool coalesce; 7901 const size_t left = pointer_delta(fc_addr, freeFinger()); 7902 const size_t right = chunkSize; 7903 switch (FLSCoalescePolicy) { 7904 // numeric value forms a coalition aggressiveness metric 7905 case 0: { // never coalesce 7906 coalesce = false; 7907 break; 7908 } 7909 case 1: { // coalesce if left & right chunks on overpopulated lists 7910 coalesce = _sp->coalOverPopulated(left) && 7911 _sp->coalOverPopulated(right); 7912 break; 7913 } 7914 case 2: { // coalesce if left chunk on overpopulated list (default) 7915 coalesce = _sp->coalOverPopulated(left); 7916 break; 7917 } 7918 case 3: { // coalesce if left OR right chunk on overpopulated list 7919 coalesce = _sp->coalOverPopulated(left) || 7920 _sp->coalOverPopulated(right); 7921 break; 7922 } 7923 case 4: { // always coalesce 7924 coalesce = true; 7925 break; 7926 } 7927 default: 7928 ShouldNotReachHere(); 7929 } 7930 7931 // Should the current free range be coalesced? 7932 // If the chunk is in a free range and either we decided to coalesce above 7933 // or the chunk is near the large block at the end of the heap 7934 // (isNearLargestChunk() returns true), then coalesce this chunk. 7935 const bool doCoalesce = inFreeRange() 7936 && (coalesce || _g->isNearLargestChunk(fc_addr)); 7937 if (doCoalesce) { 7938 // Coalesce the current free range on the left with the new 7939 // chunk on the right. If either is on a free list, 7940 // it must be removed from the list and stashed in the closure. 7941 if (freeRangeInFreeLists()) { 7942 FreeChunk* const ffc = (FreeChunk*)freeFinger(); 7943 assert(ffc->size() == pointer_delta(fc_addr, freeFinger()), 7944 "Size of free range is inconsistent with chunk size."); 7945 if (CMSTestInFreeList) { 7946 assert(_sp->verify_chunk_in_free_list(ffc), 7947 "Chunk is not in free lists"); 7948 } 7949 _sp->coalDeath(ffc->size()); 7950 _sp->removeFreeChunkFromFreeLists(ffc); 7951 set_freeRangeInFreeLists(false); 7952 } 7953 if (fcInFreeLists) { 7954 _sp->coalDeath(chunkSize); 7955 assert(fc->size() == chunkSize, 7956 "The chunk has the wrong size or is not in the free lists"); 7957 _sp->removeFreeChunkFromFreeLists(fc); 7958 } 7959 set_lastFreeRangeCoalesced(true); 7960 print_free_block_coalesced(fc); 7961 } else { // not in a free range and/or should not coalesce 7962 // Return the current free range and start a new one. 7963 if (inFreeRange()) { 7964 // In a free range but cannot coalesce with the right hand chunk. 7965 // Put the current free range into the free lists. 7966 flush_cur_free_chunk(freeFinger(), 7967 pointer_delta(fc_addr, freeFinger())); 7968 } 7969 // Set up for new free range. Pass along whether the right hand 7970 // chunk is in the free lists. 7971 initialize_free_range((HeapWord*)fc, fcInFreeLists); 7972 } 7973 } 7974 7975 // Lookahead flush: 7976 // If we are tracking a free range, and this is the last chunk that 7977 // we'll look at because its end crosses past _limit, we'll preemptively 7978 // flush it along with any free range we may be holding on to. Note that 7979 // this can be the case only for an already free or freshly garbage 7980 // chunk. If this block is an object, it can never straddle 7981 // over _limit. The "straddling" occurs when _limit is set at 7982 // the previous end of the space when this cycle started, and 7983 // a subsequent heap expansion caused the previously co-terminal 7984 // free block to be coalesced with the newly expanded portion, 7985 // thus rendering _limit a non-block-boundary making it dangerous 7986 // for the sweeper to step over and examine. 7987 void SweepClosure::lookahead_and_flush(FreeChunk* fc, size_t chunk_size) { 7988 assert(inFreeRange(), "Should only be called if currently in a free range."); 7989 HeapWord* const eob = ((HeapWord*)fc) + chunk_size; 7990 assert(_sp->used_region().contains(eob - 1), 7991 err_msg("eob = " PTR_FORMAT " eob-1 = " PTR_FORMAT " _limit = " PTR_FORMAT 7992 " out of bounds wrt _sp = [" PTR_FORMAT "," PTR_FORMAT ")" 7993 " when examining fc = " PTR_FORMAT "(" SIZE_FORMAT ")", 7994 eob, eob-1, _limit, _sp->bottom(), _sp->end(), fc, chunk_size)); 7995 if (eob >= _limit) { 7996 assert(eob == _limit || fc->is_free(), "Only a free chunk should allow us to cross over the limit"); 7997 if (CMSTraceSweeper) { 7998 gclog_or_tty->print_cr("_limit " PTR_FORMAT " reached or crossed by block " 7999 "[" PTR_FORMAT "," PTR_FORMAT ") in space " 8000 "[" PTR_FORMAT "," PTR_FORMAT ")", 8001 _limit, fc, eob, _sp->bottom(), _sp->end()); 8002 } 8003 // Return the storage we are tracking back into the free lists. 8004 if (CMSTraceSweeper) { 8005 gclog_or_tty->print_cr("Flushing ... "); 8006 } 8007 assert(freeFinger() < eob, "Error"); 8008 flush_cur_free_chunk( freeFinger(), pointer_delta(eob, freeFinger())); 8009 } 8010 } 8011 8012 void SweepClosure::flush_cur_free_chunk(HeapWord* chunk, size_t size) { 8013 assert(inFreeRange(), "Should only be called if currently in a free range."); 8014 assert(size > 0, 8015 "A zero sized chunk cannot be added to the free lists."); 8016 if (!freeRangeInFreeLists()) { 8017 if (CMSTestInFreeList) { 8018 FreeChunk* fc = (FreeChunk*) chunk; 8019 fc->set_size(size); 8020 assert(!_sp->verify_chunk_in_free_list(fc), 8021 "chunk should not be in free lists yet"); 8022 } 8023 if (CMSTraceSweeper) { 8024 gclog_or_tty->print_cr(" -- add free block " PTR_FORMAT " (" SIZE_FORMAT ") to free lists", 8025 chunk, size); 8026 } 8027 // A new free range is going to be starting. The current 8028 // free range has not been added to the free lists yet or 8029 // was removed so add it back. 8030 // If the current free range was coalesced, then the death 8031 // of the free range was recorded. Record a birth now. 8032 if (lastFreeRangeCoalesced()) { 8033 _sp->coalBirth(size); 8034 } 8035 _sp->addChunkAndRepairOffsetTable(chunk, size, 8036 lastFreeRangeCoalesced()); 8037 } else if (CMSTraceSweeper) { 8038 gclog_or_tty->print_cr("Already in free list: nothing to flush"); 8039 } 8040 set_inFreeRange(false); 8041 set_freeRangeInFreeLists(false); 8042 } 8043 8044 // We take a break if we've been at this for a while, 8045 // so as to avoid monopolizing the locks involved. 8046 void SweepClosure::do_yield_work(HeapWord* addr) { 8047 // Return current free chunk being used for coalescing (if any) 8048 // to the appropriate freelist. After yielding, the next 8049 // free block encountered will start a coalescing range of 8050 // free blocks. If the next free block is adjacent to the 8051 // chunk just flushed, they will need to wait for the next 8052 // sweep to be coalesced. 8053 if (inFreeRange()) { 8054 flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger())); 8055 } 8056 8057 // First give up the locks, then yield, then re-lock. 8058 // We should probably use a constructor/destructor idiom to 8059 // do this unlock/lock or modify the MutexUnlocker class to 8060 // serve our purpose. XXX 8061 assert_lock_strong(_bitMap->lock()); 8062 assert_lock_strong(_freelistLock); 8063 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 8064 "CMS thread should hold CMS token"); 8065 _bitMap->lock()->unlock(); 8066 _freelistLock->unlock(); 8067 ConcurrentMarkSweepThread::desynchronize(true); 8068 _collector->stopTimer(); 8069 if (PrintCMSStatistics != 0) { 8070 _collector->incrementYields(); 8071 } 8072 8073 // See the comment in coordinator_yield() 8074 for (unsigned i = 0; i < CMSYieldSleepCount && 8075 ConcurrentMarkSweepThread::should_yield() && 8076 !CMSCollector::foregroundGCIsActive(); ++i) { 8077 os::sleep(Thread::current(), 1, false); 8078 } 8079 8080 ConcurrentMarkSweepThread::synchronize(true); 8081 _freelistLock->lock(); 8082 _bitMap->lock()->lock_without_safepoint_check(); 8083 _collector->startTimer(); 8084 } 8085 8086 #ifndef PRODUCT 8087 // This is actually very useful in a product build if it can 8088 // be called from the debugger. Compile it into the product 8089 // as needed. 8090 bool debug_verify_chunk_in_free_list(FreeChunk* fc) { 8091 return debug_cms_space->verify_chunk_in_free_list(fc); 8092 } 8093 #endif 8094 8095 void SweepClosure::print_free_block_coalesced(FreeChunk* fc) const { 8096 if (CMSTraceSweeper) { 8097 gclog_or_tty->print_cr("Sweep:coal_free_blk " PTR_FORMAT " (" SIZE_FORMAT ")", 8098 fc, fc->size()); 8099 } 8100 } 8101 8102 // CMSIsAliveClosure 8103 bool CMSIsAliveClosure::do_object_b(oop obj) { 8104 HeapWord* addr = (HeapWord*)obj; 8105 return addr != NULL && 8106 (!_span.contains(addr) || _bit_map->isMarked(addr)); 8107 } 8108 8109 8110 CMSKeepAliveClosure::CMSKeepAliveClosure( CMSCollector* collector, 8111 MemRegion span, 8112 CMSBitMap* bit_map, CMSMarkStack* mark_stack, 8113 bool cpc): 8114 _collector(collector), 8115 _span(span), 8116 _bit_map(bit_map), 8117 _mark_stack(mark_stack), 8118 _concurrent_precleaning(cpc) { 8119 assert(!_span.is_empty(), "Empty span could spell trouble"); 8120 } 8121 8122 8123 // CMSKeepAliveClosure: the serial version 8124 void CMSKeepAliveClosure::do_oop(oop obj) { 8125 HeapWord* addr = (HeapWord*)obj; 8126 if (_span.contains(addr) && 8127 !_bit_map->isMarked(addr)) { 8128 _bit_map->mark(addr); 8129 bool simulate_overflow = false; 8130 NOT_PRODUCT( 8131 if (CMSMarkStackOverflowALot && 8132 _collector->simulate_overflow()) { 8133 // simulate a stack overflow 8134 simulate_overflow = true; 8135 } 8136 ) 8137 if (simulate_overflow || !_mark_stack->push(obj)) { 8138 if (_concurrent_precleaning) { 8139 // We dirty the overflown object and let the remark 8140 // phase deal with it. 8141 assert(_collector->overflow_list_is_empty(), "Error"); 8142 // In the case of object arrays, we need to dirty all of 8143 // the cards that the object spans. No locking or atomics 8144 // are needed since no one else can be mutating the mod union 8145 // table. 8146 if (obj->is_objArray()) { 8147 size_t sz = obj->size(); 8148 HeapWord* end_card_addr = 8149 (HeapWord*)round_to((intptr_t)(addr+sz), CardTableModRefBS::card_size); 8150 MemRegion redirty_range = MemRegion(addr, end_card_addr); 8151 assert(!redirty_range.is_empty(), "Arithmetical tautology"); 8152 _collector->_modUnionTable.mark_range(redirty_range); 8153 } else { 8154 _collector->_modUnionTable.mark(addr); 8155 } 8156 _collector->_ser_kac_preclean_ovflw++; 8157 } else { 8158 _collector->push_on_overflow_list(obj); 8159 _collector->_ser_kac_ovflw++; 8160 } 8161 } 8162 } 8163 } 8164 8165 void CMSKeepAliveClosure::do_oop(oop* p) { CMSKeepAliveClosure::do_oop_work(p); } 8166 void CMSKeepAliveClosure::do_oop(narrowOop* p) { CMSKeepAliveClosure::do_oop_work(p); } 8167 8168 // CMSParKeepAliveClosure: a parallel version of the above. 8169 // The work queues are private to each closure (thread), 8170 // but (may be) available for stealing by other threads. 8171 void CMSParKeepAliveClosure::do_oop(oop obj) { 8172 HeapWord* addr = (HeapWord*)obj; 8173 if (_span.contains(addr) && 8174 !_bit_map->isMarked(addr)) { 8175 // In general, during recursive tracing, several threads 8176 // may be concurrently getting here; the first one to 8177 // "tag" it, claims it. 8178 if (_bit_map->par_mark(addr)) { 8179 bool res = _work_queue->push(obj); 8180 assert(res, "Low water mark should be much less than capacity"); 8181 // Do a recursive trim in the hope that this will keep 8182 // stack usage lower, but leave some oops for potential stealers 8183 trim_queue(_low_water_mark); 8184 } // Else, another thread got there first 8185 } 8186 } 8187 8188 void CMSParKeepAliveClosure::do_oop(oop* p) { CMSParKeepAliveClosure::do_oop_work(p); } 8189 void CMSParKeepAliveClosure::do_oop(narrowOop* p) { CMSParKeepAliveClosure::do_oop_work(p); } 8190 8191 void CMSParKeepAliveClosure::trim_queue(uint max) { 8192 while (_work_queue->size() > max) { 8193 oop new_oop; 8194 if (_work_queue->pop_local(new_oop)) { 8195 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop"); 8196 assert(_bit_map->isMarked((HeapWord*)new_oop), 8197 "no white objects on this stack!"); 8198 assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop"); 8199 // iterate over the oops in this oop, marking and pushing 8200 // the ones in CMS heap (i.e. in _span). 8201 new_oop->oop_iterate(&_mark_and_push); 8202 } 8203 } 8204 } 8205 8206 CMSInnerParMarkAndPushClosure::CMSInnerParMarkAndPushClosure( 8207 CMSCollector* collector, 8208 MemRegion span, CMSBitMap* bit_map, 8209 OopTaskQueue* work_queue): 8210 _collector(collector), 8211 _span(span), 8212 _bit_map(bit_map), 8213 _work_queue(work_queue) { } 8214 8215 void CMSInnerParMarkAndPushClosure::do_oop(oop obj) { 8216 HeapWord* addr = (HeapWord*)obj; 8217 if (_span.contains(addr) && 8218 !_bit_map->isMarked(addr)) { 8219 if (_bit_map->par_mark(addr)) { 8220 bool simulate_overflow = false; 8221 NOT_PRODUCT( 8222 if (CMSMarkStackOverflowALot && 8223 _collector->par_simulate_overflow()) { 8224 // simulate a stack overflow 8225 simulate_overflow = true; 8226 } 8227 ) 8228 if (simulate_overflow || !_work_queue->push(obj)) { 8229 _collector->par_push_on_overflow_list(obj); 8230 _collector->_par_kac_ovflw++; 8231 } 8232 } // Else another thread got there already 8233 } 8234 } 8235 8236 void CMSInnerParMarkAndPushClosure::do_oop(oop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); } 8237 void CMSInnerParMarkAndPushClosure::do_oop(narrowOop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); } 8238 8239 ////////////////////////////////////////////////////////////////// 8240 // CMSExpansionCause ///////////////////////////// 8241 ////////////////////////////////////////////////////////////////// 8242 const char* CMSExpansionCause::to_string(CMSExpansionCause::Cause cause) { 8243 switch (cause) { 8244 case _no_expansion: 8245 return "No expansion"; 8246 case _satisfy_free_ratio: 8247 return "Free ratio"; 8248 case _satisfy_promotion: 8249 return "Satisfy promotion"; 8250 case _satisfy_allocation: 8251 return "allocation"; 8252 case _allocate_par_lab: 8253 return "Par LAB"; 8254 case _allocate_par_spooling_space: 8255 return "Par Spooling Space"; 8256 case _adaptive_size_policy: 8257 return "Ergonomics"; 8258 default: 8259 return "unknown"; 8260 } 8261 } 8262 8263 void CMSDrainMarkingStackClosure::do_void() { 8264 // the max number to take from overflow list at a time 8265 const size_t num = _mark_stack->capacity()/4; 8266 assert(!_concurrent_precleaning || _collector->overflow_list_is_empty(), 8267 "Overflow list should be NULL during concurrent phases"); 8268 while (!_mark_stack->isEmpty() || 8269 // if stack is empty, check the overflow list 8270 _collector->take_from_overflow_list(num, _mark_stack)) { 8271 oop obj = _mark_stack->pop(); 8272 HeapWord* addr = (HeapWord*)obj; 8273 assert(_span.contains(addr), "Should be within span"); 8274 assert(_bit_map->isMarked(addr), "Should be marked"); 8275 assert(obj->is_oop(), "Should be an oop"); 8276 obj->oop_iterate(_keep_alive); 8277 } 8278 } 8279 8280 void CMSParDrainMarkingStackClosure::do_void() { 8281 // drain queue 8282 trim_queue(0); 8283 } 8284 8285 // Trim our work_queue so its length is below max at return 8286 void CMSParDrainMarkingStackClosure::trim_queue(uint max) { 8287 while (_work_queue->size() > max) { 8288 oop new_oop; 8289 if (_work_queue->pop_local(new_oop)) { 8290 assert(new_oop->is_oop(), "Expected an oop"); 8291 assert(_bit_map->isMarked((HeapWord*)new_oop), 8292 "no white objects on this stack!"); 8293 assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop"); 8294 // iterate over the oops in this oop, marking and pushing 8295 // the ones in CMS heap (i.e. in _span). 8296 new_oop->oop_iterate(&_mark_and_push); 8297 } 8298 } 8299 } 8300 8301 //////////////////////////////////////////////////////////////////// 8302 // Support for Marking Stack Overflow list handling and related code 8303 //////////////////////////////////////////////////////////////////// 8304 // Much of the following code is similar in shape and spirit to the 8305 // code used in ParNewGC. We should try and share that code 8306 // as much as possible in the future. 8307 8308 #ifndef PRODUCT 8309 // Debugging support for CMSStackOverflowALot 8310 8311 // It's OK to call this multi-threaded; the worst thing 8312 // that can happen is that we'll get a bunch of closely 8313 // spaced simulated overflows, but that's OK, in fact 8314 // probably good as it would exercise the overflow code 8315 // under contention. 8316 bool CMSCollector::simulate_overflow() { 8317 if (_overflow_counter-- <= 0) { // just being defensive 8318 _overflow_counter = CMSMarkStackOverflowInterval; 8319 return true; 8320 } else { 8321 return false; 8322 } 8323 } 8324 8325 bool CMSCollector::par_simulate_overflow() { 8326 return simulate_overflow(); 8327 } 8328 #endif 8329 8330 // Single-threaded 8331 bool CMSCollector::take_from_overflow_list(size_t num, CMSMarkStack* stack) { 8332 assert(stack->isEmpty(), "Expected precondition"); 8333 assert(stack->capacity() > num, "Shouldn't bite more than can chew"); 8334 size_t i = num; 8335 oop cur = _overflow_list; 8336 const markOop proto = markOopDesc::prototype(); 8337 NOT_PRODUCT(ssize_t n = 0;) 8338 for (oop next; i > 0 && cur != NULL; cur = next, i--) { 8339 next = oop(cur->mark()); 8340 cur->set_mark(proto); // until proven otherwise 8341 assert(cur->is_oop(), "Should be an oop"); 8342 bool res = stack->push(cur); 8343 assert(res, "Bit off more than can chew?"); 8344 NOT_PRODUCT(n++;) 8345 } 8346 _overflow_list = cur; 8347 #ifndef PRODUCT 8348 assert(_num_par_pushes >= n, "Too many pops?"); 8349 _num_par_pushes -=n; 8350 #endif 8351 return !stack->isEmpty(); 8352 } 8353 8354 #define BUSY (cast_to_oop<intptr_t>(0x1aff1aff)) 8355 // (MT-safe) Get a prefix of at most "num" from the list. 8356 // The overflow list is chained through the mark word of 8357 // each object in the list. We fetch the entire list, 8358 // break off a prefix of the right size and return the 8359 // remainder. If other threads try to take objects from 8360 // the overflow list at that time, they will wait for 8361 // some time to see if data becomes available. If (and 8362 // only if) another thread places one or more object(s) 8363 // on the global list before we have returned the suffix 8364 // to the global list, we will walk down our local list 8365 // to find its end and append the global list to 8366 // our suffix before returning it. This suffix walk can 8367 // prove to be expensive (quadratic in the amount of traffic) 8368 // when there are many objects in the overflow list and 8369 // there is much producer-consumer contention on the list. 8370 // *NOTE*: The overflow list manipulation code here and 8371 // in ParNewGeneration:: are very similar in shape, 8372 // except that in the ParNew case we use the old (from/eden) 8373 // copy of the object to thread the list via its klass word. 8374 // Because of the common code, if you make any changes in 8375 // the code below, please check the ParNew version to see if 8376 // similar changes might be needed. 8377 // CR 6797058 has been filed to consolidate the common code. 8378 bool CMSCollector::par_take_from_overflow_list(size_t num, 8379 OopTaskQueue* work_q, 8380 int no_of_gc_threads) { 8381 assert(work_q->size() == 0, "First empty local work queue"); 8382 assert(num < work_q->max_elems(), "Can't bite more than we can chew"); 8383 if (_overflow_list == NULL) { 8384 return false; 8385 } 8386 // Grab the entire list; we'll put back a suffix 8387 oop prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list)); 8388 Thread* tid = Thread::current(); 8389 // Before "no_of_gc_threads" was introduced CMSOverflowSpinCount was 8390 // set to ParallelGCThreads. 8391 size_t CMSOverflowSpinCount = (size_t) no_of_gc_threads; // was ParallelGCThreads; 8392 size_t sleep_time_millis = MAX2((size_t)1, num/100); 8393 // If the list is busy, we spin for a short while, 8394 // sleeping between attempts to get the list. 8395 for (size_t spin = 0; prefix == BUSY && spin < CMSOverflowSpinCount; spin++) { 8396 os::sleep(tid, sleep_time_millis, false); 8397 if (_overflow_list == NULL) { 8398 // Nothing left to take 8399 return false; 8400 } else if (_overflow_list != BUSY) { 8401 // Try and grab the prefix 8402 prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list)); 8403 } 8404 } 8405 // If the list was found to be empty, or we spun long 8406 // enough, we give up and return empty-handed. If we leave 8407 // the list in the BUSY state below, it must be the case that 8408 // some other thread holds the overflow list and will set it 8409 // to a non-BUSY state in the future. 8410 if (prefix == NULL || prefix == BUSY) { 8411 // Nothing to take or waited long enough 8412 if (prefix == NULL) { 8413 // Write back the NULL in case we overwrote it with BUSY above 8414 // and it is still the same value. 8415 (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY); 8416 } 8417 return false; 8418 } 8419 assert(prefix != NULL && prefix != BUSY, "Error"); 8420 size_t i = num; 8421 oop cur = prefix; 8422 // Walk down the first "num" objects, unless we reach the end. 8423 for (; i > 1 && cur->mark() != NULL; cur = oop(cur->mark()), i--); 8424 if (cur->mark() == NULL) { 8425 // We have "num" or fewer elements in the list, so there 8426 // is nothing to return to the global list. 8427 // Write back the NULL in lieu of the BUSY we wrote 8428 // above, if it is still the same value. 8429 if (_overflow_list == BUSY) { 8430 (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY); 8431 } 8432 } else { 8433 // Chop off the suffix and return it to the global list. 8434 assert(cur->mark() != BUSY, "Error"); 8435 oop suffix_head = cur->mark(); // suffix will be put back on global list 8436 cur->set_mark(NULL); // break off suffix 8437 // It's possible that the list is still in the empty(busy) state 8438 // we left it in a short while ago; in that case we may be 8439 // able to place back the suffix without incurring the cost 8440 // of a walk down the list. 8441 oop observed_overflow_list = _overflow_list; 8442 oop cur_overflow_list = observed_overflow_list; 8443 bool attached = false; 8444 while (observed_overflow_list == BUSY || observed_overflow_list == NULL) { 8445 observed_overflow_list = 8446 (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list); 8447 if (cur_overflow_list == observed_overflow_list) { 8448 attached = true; 8449 break; 8450 } else cur_overflow_list = observed_overflow_list; 8451 } 8452 if (!attached) { 8453 // Too bad, someone else sneaked in (at least) an element; we'll need 8454 // to do a splice. Find tail of suffix so we can prepend suffix to global 8455 // list. 8456 for (cur = suffix_head; cur->mark() != NULL; cur = (oop)(cur->mark())); 8457 oop suffix_tail = cur; 8458 assert(suffix_tail != NULL && suffix_tail->mark() == NULL, 8459 "Tautology"); 8460 observed_overflow_list = _overflow_list; 8461 do { 8462 cur_overflow_list = observed_overflow_list; 8463 if (cur_overflow_list != BUSY) { 8464 // Do the splice ... 8465 suffix_tail->set_mark(markOop(cur_overflow_list)); 8466 } else { // cur_overflow_list == BUSY 8467 suffix_tail->set_mark(NULL); 8468 } 8469 // ... and try to place spliced list back on overflow_list ... 8470 observed_overflow_list = 8471 (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list); 8472 } while (cur_overflow_list != observed_overflow_list); 8473 // ... until we have succeeded in doing so. 8474 } 8475 } 8476 8477 // Push the prefix elements on work_q 8478 assert(prefix != NULL, "control point invariant"); 8479 const markOop proto = markOopDesc::prototype(); 8480 oop next; 8481 NOT_PRODUCT(ssize_t n = 0;) 8482 for (cur = prefix; cur != NULL; cur = next) { 8483 next = oop(cur->mark()); 8484 cur->set_mark(proto); // until proven otherwise 8485 assert(cur->is_oop(), "Should be an oop"); 8486 bool res = work_q->push(cur); 8487 assert(res, "Bit off more than we can chew?"); 8488 NOT_PRODUCT(n++;) 8489 } 8490 #ifndef PRODUCT 8491 assert(_num_par_pushes >= n, "Too many pops?"); 8492 Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes); 8493 #endif 8494 return true; 8495 } 8496 8497 // Single-threaded 8498 void CMSCollector::push_on_overflow_list(oop p) { 8499 NOT_PRODUCT(_num_par_pushes++;) 8500 assert(p->is_oop(), "Not an oop"); 8501 preserve_mark_if_necessary(p); 8502 p->set_mark((markOop)_overflow_list); 8503 _overflow_list = p; 8504 } 8505 8506 // Multi-threaded; use CAS to prepend to overflow list 8507 void CMSCollector::par_push_on_overflow_list(oop p) { 8508 NOT_PRODUCT(Atomic::inc_ptr(&_num_par_pushes);) 8509 assert(p->is_oop(), "Not an oop"); 8510 par_preserve_mark_if_necessary(p); 8511 oop observed_overflow_list = _overflow_list; 8512 oop cur_overflow_list; 8513 do { 8514 cur_overflow_list = observed_overflow_list; 8515 if (cur_overflow_list != BUSY) { 8516 p->set_mark(markOop(cur_overflow_list)); 8517 } else { 8518 p->set_mark(NULL); 8519 } 8520 observed_overflow_list = 8521 (oop) Atomic::cmpxchg_ptr(p, &_overflow_list, cur_overflow_list); 8522 } while (cur_overflow_list != observed_overflow_list); 8523 } 8524 #undef BUSY 8525 8526 // Single threaded 8527 // General Note on GrowableArray: pushes may silently fail 8528 // because we are (temporarily) out of C-heap for expanding 8529 // the stack. The problem is quite ubiquitous and affects 8530 // a lot of code in the JVM. The prudent thing for GrowableArray 8531 // to do (for now) is to exit with an error. However, that may 8532 // be too draconian in some cases because the caller may be 8533 // able to recover without much harm. For such cases, we 8534 // should probably introduce a "soft_push" method which returns 8535 // an indication of success or failure with the assumption that 8536 // the caller may be able to recover from a failure; code in 8537 // the VM can then be changed, incrementally, to deal with such 8538 // failures where possible, thus, incrementally hardening the VM 8539 // in such low resource situations. 8540 void CMSCollector::preserve_mark_work(oop p, markOop m) { 8541 _preserved_oop_stack.push(p); 8542 _preserved_mark_stack.push(m); 8543 assert(m == p->mark(), "Mark word changed"); 8544 assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(), 8545 "bijection"); 8546 } 8547 8548 // Single threaded 8549 void CMSCollector::preserve_mark_if_necessary(oop p) { 8550 markOop m = p->mark(); 8551 if (m->must_be_preserved(p)) { 8552 preserve_mark_work(p, m); 8553 } 8554 } 8555 8556 void CMSCollector::par_preserve_mark_if_necessary(oop p) { 8557 markOop m = p->mark(); 8558 if (m->must_be_preserved(p)) { 8559 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag); 8560 // Even though we read the mark word without holding 8561 // the lock, we are assured that it will not change 8562 // because we "own" this oop, so no other thread can 8563 // be trying to push it on the overflow list; see 8564 // the assertion in preserve_mark_work() that checks 8565 // that m == p->mark(). 8566 preserve_mark_work(p, m); 8567 } 8568 } 8569 8570 // We should be able to do this multi-threaded, 8571 // a chunk of stack being a task (this is 8572 // correct because each oop only ever appears 8573 // once in the overflow list. However, it's 8574 // not very easy to completely overlap this with 8575 // other operations, so will generally not be done 8576 // until all work's been completed. Because we 8577 // expect the preserved oop stack (set) to be small, 8578 // it's probably fine to do this single-threaded. 8579 // We can explore cleverer concurrent/overlapped/parallel 8580 // processing of preserved marks if we feel the 8581 // need for this in the future. Stack overflow should 8582 // be so rare in practice and, when it happens, its 8583 // effect on performance so great that this will 8584 // likely just be in the noise anyway. 8585 void CMSCollector::restore_preserved_marks_if_any() { 8586 assert(SafepointSynchronize::is_at_safepoint(), 8587 "world should be stopped"); 8588 assert(Thread::current()->is_ConcurrentGC_thread() || 8589 Thread::current()->is_VM_thread(), 8590 "should be single-threaded"); 8591 assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(), 8592 "bijection"); 8593 8594 while (!_preserved_oop_stack.is_empty()) { 8595 oop p = _preserved_oop_stack.pop(); 8596 assert(p->is_oop(), "Should be an oop"); 8597 assert(_span.contains(p), "oop should be in _span"); 8598 assert(p->mark() == markOopDesc::prototype(), 8599 "Set when taken from overflow list"); 8600 markOop m = _preserved_mark_stack.pop(); 8601 p->set_mark(m); 8602 } 8603 assert(_preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty(), 8604 "stacks were cleared above"); 8605 } 8606 8607 #ifndef PRODUCT 8608 bool CMSCollector::no_preserved_marks() const { 8609 return _preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty(); 8610 } 8611 #endif 8612 8613 // Transfer some number of overflown objects to usual marking 8614 // stack. Return true if some objects were transferred. 8615 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() { 8616 size_t num = MIN2((size_t)(_mark_stack->capacity() - _mark_stack->length())/4, 8617 (size_t)ParGCDesiredObjsFromOverflowList); 8618 8619 bool res = _collector->take_from_overflow_list(num, _mark_stack); 8620 assert(_collector->overflow_list_is_empty() || res, 8621 "If list is not empty, we should have taken something"); 8622 assert(!res || !_mark_stack->isEmpty(), 8623 "If we took something, it should now be on our stack"); 8624 return res; 8625 } 8626 8627 size_t MarkDeadObjectsClosure::do_blk(HeapWord* addr) { 8628 size_t res = _sp->block_size_no_stall(addr, _collector); 8629 if (_sp->block_is_obj(addr)) { 8630 if (_live_bit_map->isMarked(addr)) { 8631 // It can't have been dead in a previous cycle 8632 guarantee(!_dead_bit_map->isMarked(addr), "No resurrection!"); 8633 } else { 8634 _dead_bit_map->mark(addr); // mark the dead object 8635 } 8636 } 8637 // Could be 0, if the block size could not be computed without stalling. 8638 return res; 8639 } 8640 8641 TraceCMSMemoryManagerStats::TraceCMSMemoryManagerStats(CMSCollector::CollectorState phase, GCCause::Cause cause): TraceMemoryManagerStats() { 8642 8643 switch (phase) { 8644 case CMSCollector::InitialMarking: 8645 initialize(true /* fullGC */ , 8646 cause /* cause of the GC */, 8647 true /* recordGCBeginTime */, 8648 true /* recordPreGCUsage */, 8649 false /* recordPeakUsage */, 8650 false /* recordPostGCusage */, 8651 true /* recordAccumulatedGCTime */, 8652 false /* recordGCEndTime */, 8653 false /* countCollection */ ); 8654 break; 8655 8656 case CMSCollector::FinalMarking: 8657 initialize(true /* fullGC */ , 8658 cause /* cause of the GC */, 8659 false /* recordGCBeginTime */, 8660 false /* recordPreGCUsage */, 8661 false /* recordPeakUsage */, 8662 false /* recordPostGCusage */, 8663 true /* recordAccumulatedGCTime */, 8664 false /* recordGCEndTime */, 8665 false /* countCollection */ ); 8666 break; 8667 8668 case CMSCollector::Sweeping: 8669 initialize(true /* fullGC */ , 8670 cause /* cause of the GC */, 8671 false /* recordGCBeginTime */, 8672 false /* recordPreGCUsage */, 8673 true /* recordPeakUsage */, 8674 true /* recordPostGCusage */, 8675 false /* recordAccumulatedGCTime */, 8676 true /* recordGCEndTime */, 8677 true /* countCollection */ ); 8678 break; 8679 8680 default: 8681 ShouldNotReachHere(); 8682 } 8683 }