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